Shiny 应用程序中的绘图是一条平线而不是工作散点图

Ploly graph in Shiny application is a flat line instead of working scatter plot

我正在与 shiny 合作创建一个下拉框,您可以在其中 select 一个项目。当 selected 该项目时,会显示一个绘图图。当我 运行 绘图本身时,我得到了一个漂亮的散点图,但是当我 运行 它在闪亮的应用程序中时,我在三个项目中的每一个上都得到了一条直线。

这是在 运行 本身时有效的情节代码:

library(plotly)
plot_ly(df1, x = ~time, y = ~item1, color = ~item1) 
%>% add_lines(name = ~"item1")

这是包含 4 列和 26949 行的数据集:

      time                      item1    item2    item3
1     2018-04-09 00:00:06        615       NA       NA
2     2018-04-09 00:00:08         NA      465       NA
3     2018-04-09 00:00:08         NA       NA       NA
4     2018-04-09 00:00:10         NA       NA      422
5     2018-04-09 00:00:13         NA       NA       NA
6     2018-04-09 00:00:21        522       NA      385
7     2018-04-09 00:00:25         NA       NA       NA
....  ....                       ....     ....     ...
26949 2018-04-09 23:59:59        323       NA      200

Shiny代码如下:

#Import libraries
library(shiny)
library(plotly)

# Define UI for the application
ui <- bootstrapPage(

selectInput(inputId = "n_breaks",
            label = "Select Item:",
            choices = c("item1", "item2", "item3"),
            selected = "item1"),

plotlyOutput(outputId = "main_plot", height = "300px")

)

# Define server logic
server <- function(input, output) {

#Import data
df = read.csv("item_list.csv")

output$main_plot <- renderPlotly({

#Plotly graph
plot_ly(df, x = ~time, y = ~input$n_breaks, color = ~input$n_breaks) %>%
  add_lines(name = ~input$n_breaks)
})
}

# Run the application 
shinyApp(ui = ui, server = server)

在大多数情况下,此代码有效,但图表混乱。任何帮助将不胜感激!

您应该将 plot_ly 函数编写为:

plot_ly(df, x = ~time, 
        y = df[, input$n_breaks], 
        color = df[, input$n_breaks]) %>%
        add_lines(name = ~input$n_breaks)

或者更短一点:

plot_ly(x = df[, "time"], 
        y = df[, input$n_breaks], 
        color = df[, input$n_breaks]) %>%
        add_lines(name = ~input$n_breaks)