我有一个具有不同列的数据框。第一个是年份,其余的是不同品牌。我想绘制一张图表,显示这些不同品牌多年来在利润方面的表现。该图表应该有一个下拉菜单,允许您选择您想要查看的公司,这是一个包含所有品牌的下拉复选框。该复选框还应该允许您同时看到所有这些,或只是其中一些。
\n\n#Here is my go at it.\n\nlibrary(plotly)\nx <- seq(-2 * pi, 2 * pi, length.out = 1000)\ndf <- data.frame(x, y1 = sin(x), y2 = cos(x), y3=cos(2*x), y4=sin(3*x))\n\np <- plot_ly(df, x = ~x) %>%\n add_lines(y = ~y1, name = "Sin") %>%\n add_lines(y = ~y2, name = "Cos", visible = F) %>%\n layout(\n title = "Drop down menus - Styling",\n xaxis = list(domain = c(0.1, 1)),\n yaxis = list(title = "y"),\n updatemenus = list(\n\n list(\n y = 0.7,\n buttons = list(\n list(method = "restyle",\n args = list("visible", list(TRUE, FALSE)),\n label = "Sinx"),\n\n list(method = "restyle",\n args = list("visible", list(FALSE, TRUE)),\n label = "Cosx")))\n )\n )\np \nRun Code Online (Sandbox Code Playgroud)\n\n
\n在上面的示例中,我能够创建一个下拉菜单,但它与我想要的并不接近。另外,我无法\xe2\x80\x99t掌握这个问题给出的答案,因为它使用了太多的html(我很擅长html)。任何帮助是极大的赞赏。
您链接的问题使用闪亮,但您似乎没有使用闪亮。
这是一种非常接近您想要的非闪亮方法。它使用长格式数据上的crosstalk::SharedDataandcrosstalk::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)
Run Code Online (Sandbox Code Playgroud)
如果您不知道,单击绘图图例中的系列将切换该系列的可见性。因此,您可能根本不需要下拉菜单,只需执行以下操作即可:
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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1511 次 |
| 最近记录: |