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

时间:2018-04-11 13:40:38

标签: r shiny plotly r-plotly

我正在使用闪亮来创建一个下拉框,您可以在其中选择一个项目。选择该项目后,将显示绘图图表。当我单独运行图形图时,我得到了一个漂亮的散点图,但是当我在闪亮的应用程序中运行它时,我会在这三个项目中得到一条直线。

这是在单独运行时有效的图形代码:

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)

在大多数情况下,这段代码可以正常工作,但图表搞砸了。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您应该将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)