【问题标题】:Interactive charts in plotly using dynamic input fields使用动态输入字段绘制交互式图表
【发布时间】:2019-02-18 11:27:42
【问题描述】:

我正在尝试创建一个具有下拉列表的图表,用户可以在其中选择要在图表上显示的内容(如 Power BI 图表中的“过滤器”,但我想留在 R 中)。所以我会选择 Shiny 和 Plotly(欢迎任何其他建议!)。

大多数教程都指向对输入选择进行硬编码,但我有数千个选择,因此我希望从我的数据源中的字段动态生成此列表。这是我到目前为止的示例,我希望下拉菜单让用户在 Home 1 和 Home 2 之间进行选择:

library(shiny)
library(plotly)

df <- data.frame(Name = c("Home 1", "Home 1", "Home 2", "Home 2"), Rating = c("Good", "Excellent", "Good", "Good"),
                     Date = c("2016-07-14", "2016-08-14", "2016-07-14", "2016-08-14"))


# Get a basic shiny app working with dropdowns
ui <- fluidPage(
  plotlyOutput("plot"),
  selectInput(df$Name, "Select Name", df$Name),
  verbatimTextOutput("event")
)

server <- function(input, output) { 
  output$plot <- renderPlotly({
    plot_ly(df, x = df$Date, y = df$Rating, type = 'scatter', mode = 'line')
  })

  output$event <- renderPrint({
    d <- event_data("plotly_hover")
    if (is.null(d)) "Hover on a point!" else d
  })
}

shinyApp(ui, server)

我不知道将selectInput()中的选定输入放到plot_ly()函数中的哪个位置,所以这段代码显然会抛出一堆警告并且不起作用。

Warning in if (!is.na(attribValue)) { :
  the condition has length > 1 and only the first element will be used
Warning in charToRaw(enc2utf8(text)) :
  argument should be a character vector of length 1
all but the first element will be ignored

我觉得我已经很接近了,但我已经筋疲力尽了,基本上需要比我更擅长这方面的人来为我指明正确的方向。

或者有没有更好的方法使用除了闪亮和情节之外的包?

谢谢

【问题讨论】:

    标签: r shiny r-plotly


    【解决方案1】:

    这是我的处理方法:

    library(shiny)
    library(plotly)
    
    df <- data.frame(Name = c("Home 1", "Home 1", "Home 2", "Home 2"), Rating = c("Good", "Excellent", "Good", "Good"),
                     Date = c("2016-07-14", "2016-08-14", "2016-07-14", "2016-08-14"))
    
    # Get a basic shiny app working with dropdowns
    ui <- fluidPage(
      plotlyOutput("plot"),
      selectInput("SelectName", "Select Name", df$Name, selected = unique(df$Name), multiple = TRUE),
      verbatimTextOutput("event")
    )
    
    server <- function(input, output) { 
    
      filteredDf <- reactive({
        req(input$SelectName)
        df[df$Name %in% input$SelectName, ]
      })
    
      output$plot <- renderPlotly({
        plot_ly(filteredDf(), x = ~Date, y = ~Rating, type = 'scatter', mode = 'line', color = ~Name)
      })
    
      output$event <- renderPrint({
        d <- event_data("plotly_hover")
        if (is.null(d)) "Hover on a point!" else d
      })
    }
    
    shinyApp(ui, server)
    

    您需要从您的df(我称之为filteredDf)创建一个反应式(过滤的)数据集

    【讨论】:

    • 不错!但是选定的输入对图表没有影响?首次渲染图表时会显示两个房屋,然后当我选择特定房屋时,图表没有任何反应。
    • 它确实对图表有影响。尝试使用退格键取消选择(或删除)selectInput 中的项目。
    猜你喜欢
    • 2015-11-16
    • 2016-05-08
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多