如何在闪亮的直方图中动态添加和删除叠加层

How to dynamically add AND remove overlay from plotly histogram in shiny

此 R 代码生成一个将两个直方图叠加在一起的绘图。

fig <- plot_ly(alpha = 0.6)
fig <- fig %>% add_histogram(x = ~rnorm(500))
fig <- fig %>% add_histogram(x = ~rnorm(500) + 1)
fig <- fig %>% layout(barmode = "overlay")

fig

我有一个包含可变分类输入的 shiny 应用程序。根据用户选择,我想添加或删除要在直方图中绘制的类别。如果能够动态添加或删除叠加层,那就太好了。现在似乎可以动态添加叠加层。删除它们似乎更加困难。我想知道我的要求是否可行?

编辑: @FreyGeospatial 澄清说,他想要 add/remove 痕迹(我对使用 overlay 的措辞感到困惑)。

动态添加和删除跟踪的最简单方法是创建 data.frame 提供类别列的长格式。

plot_ly 中,您可以使用 splitcolor 创建基于此列的跟踪。 要删除痕迹,您可以从反应数据集中过滤类别并重新渲染绘图:

library(shiny)
library(plotly)

DF <- data.frame(values = rnorm(2500), category = rep(LETTERS[1:5], each = 500))

ui <- fluidPage(
  selectizeInput(inputId = "barmode",
                 label = "barmode",
                 choices = c("group", "overlay", "stack"),
                 selected = "overlay"),
  selectizeInput(inputId = "category",
                 label = "category",
                 choices = unique(DF$category), selected = LETTERS[1:3], multiple = TRUE),
  plotlyOutput("myPlot")
)

server <- function(input, output, session) {
  
  filteredDF <- reactive({
    DF[DF$category %in% input$category,]
  })
  
  output$myPlot <- renderPlotly({
    fig <- plot_ly(data = filteredDF(), x = ~ values, split = ~ category, alpha = 0.6, type = "histogram")
    fig <- fig %>% layout(barmode = input$barmode)
    fig
  })
  
}

shinyApp(ui, server)

作为重新渲染绘图的替代方法,您可以使用 plotlyProxy 和 addTraces JS function please see my answer 。这比使用 plotly 的 R API.

重新渲染要快,但不够直观

请运行:

install.packages("listviewer")
schema()

并导航: object } traces } bar } layoutAttributes } barmode

查找条形码描述:

默认:组

Determines how bars at the same location coordinate are displayed on the graph. With stack, the bars are stacked on top of one another With relative, the bars are stacked on top of one another, with negative values below the axis, positive values above With group, the bars are plotted next to one another centered around the shared location. With overlay, the bars are plotted over one another, you might need to an opacity to see multiple bars.