r中的下拉菜单和复选框

时间:2019-06-26 16:46:46

标签: r plotly

我有一个具有不同列的数据框。第一个是年份,其余的是不同的品牌。我想绘制一个图表,显示这些年来不同品牌在利润方面的表现。该图应具有一个下拉菜单,允许您选择要查看的公司,即所有品牌的下拉复选框。复选框还应该允许您同时查看所有这些内容,或仅查看其中一些。

#Here is my go at it.

library(plotly)
x <- seq(-2 * pi, 2 * pi, length.out = 1000)
df <- data.frame(x, y1 = sin(x), y2 = cos(x), y3=cos(2*x), y4=sin(3*x))

p <- plot_ly(df, x = ~x) %>%
  add_lines(y = ~y1, name = "Sin") %>%
  add_lines(y = ~y2, name = "Cos", visible = F) %>%
  layout(
    title = "Drop down menus - Styling",
    xaxis = list(domain = c(0.1, 1)),
    yaxis = list(title = "y"),
    updatemenus = list(

      list(
        y = 0.7,
        buttons = list(
          list(method = "restyle",
               args = list("visible", list(TRUE, FALSE)),
               label = "Sinx"),

          list(method = "restyle",
               args = list("visible", list(FALSE, TRUE)),
               label = "Cosx")))
    )
  )
p 

enter image description here 在上面的示例中,我能够创建一个下拉菜单,但它与我想要的菜单并不接近。另外,由于该question使用了太多的html(我很喜欢html),因此我无法把握答案。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您链接的问题使用了闪亮功能,但您似乎并没有使用闪亮功能。

这是一种非发光的方法,非常接近您想要的方法。它在长格式数据上使用crosstalk::SharedDatacrosstalk::filter_select(),以提供允许多种选择的下拉类型输入。

library(crosstalk)
library(dplyr)
library(plotly)
library(tidyr)

data_wide <- tibble(x = seq(-2 * pi, 2 * pi, length.out = 1000), 
                    y0 = 0, 
                    y1 = sin(x), 
                    y2 = cos(x), 
                    y3 = cos(2 * x), 
                    y4 = sin(3 * x))

data_long <- data_wide %>% 
  gather("series", "y", -x) %>% 
  mutate(series = case_when(series == "y0" ~ "0", 
                            series == "y1" ~ "sin(x)", 
                            series == "y2" ~ "cos(x)", 
                            series == "y3" ~ "cos(2x)", 
                            series == "y4" ~ "sin(3x)"))

data_shared <- SharedData$new(data_long, key = ~series)

p <- data_shared %>% 
  plot_ly(x = ~x, y = ~y, color = ~series) %>% 
  add_lines()

bscols(widths = c(3, NA), 
       filter_select(id = "fsid", 
                     label = "Series", 
                     sharedData = data_shared, 
                     group = ~series), 
       p)

crosstalk_filter_select

如果您不知道,请在打印的图例的图例中单击序列将切换该序列的可见性。因此,您可能根本不需要下拉菜单,而可以执行以下操作:

library(plotly)

x <- seq(-2 * pi, 2 * pi, length.out = 1000)
df <- data.frame(x, y = 0, y1 = sin(x), y2 = cos(x), y3 = cos(2 * x), y4 = sin(3 * x))

plot_ly(df, type = "scatter", mode = "lines") %>% 
  add_lines(x= ~x, y= ~y,  name = "0",       line=list(color="red")) %>% 
  add_lines(x= ~x, y= ~y1, name = "sin(x)",  line=list(color="orange")) %>% 
  add_lines(x= ~x, y= ~y2, name = "cos(x)",  line=list(color="yellow")) %>% 
  add_lines(x= ~x, y= ~y3, name = "cos(2x)", line=list(color="green")) %>% 
  add_lines(x= ~x, y= ~y4, name = "sin(3x)", line=list(color="blue")) %>% 
  layout(title = "Choose Your Own Brands")

toggle visibility in legend