繁体   English   中英

我可以在不使用Shiny或Plotly的情况下使用R中的下拉菜单绘制线条图吗?

[英]Can I make a line plot with a dropdown menu in R without using Shiny or Plotly?

我想制作一个简单的销售报告折线图,从下拉菜单中显示给定产品随时间的产品销售情况。 我已经使用plotty和shiny进行了报告,但是我无法找到一种方法来与同事共享报告,而不必使用Shiny Server或Shinyapps.IO。 理想情况下,我想要一个独立的html文件,但找不到将交互式图形插入R Markdown的方法。

这是一个示例数据框:

df = data.frame(month=rep_len(1:12, length.out=12*5), product=rep(1:5, each=12),sales=rnorm(12*5,100,50)) 

以下建议几乎可行,但下拉列表与正确的变量不对应

set.seed(42)
library(plotly)

## Create random data. cols holds the parameter that should be switched
l <- lapply(1:100, function(i) rnorm(100))
df <- as.data.frame(l)
cols <- paste0(letters, 1:100)
colnames(df) <- cols
df[["c"]] <- 1:100


p <- plot_ly(df,
      type = "scatter",
      mode = "lines") %>% 
      add_lines(x = ~c, y=~df[[cols[[1]]]], name = cols[[1]])
## Add arbitrary number of traces
for (col in cols) {
  p <- p %>% add_lines(x = ~c, y = df[[col]], name = col, visible = FALSE)
}
p <- p %>%
    layout(
      title = "Dropdown line plot",
      xaxis = list(title = "x"),
      xaxis = list(title = "y"),
      updatemenus = list(
        list(
            y = 0.7,
            ## Add all buttons at once
            buttons = lapply(cols, function(col) {
              list(method="restyle", 
                args = list(
                  "visible", cols == col),
                  label = col)
            })
        )
      )
    )

print(p)

选择变量b2将显示a1和v100的行。

选择b2显示a1和v100的行

选择c3时,显示a1的行,b2的d4的行,等等。似乎该顺序是2列移位。

选择c3显示a1的行

以下示例完全满足您的要求,可以嵌入到RMarkdown中,然后转换为独立的HTML页面,可以脱机查看该页面或将其托管在服务器上:

## Create random data. cols holds the parameter that should be switched
l <- lapply(1:100, function(i) rnorm(100))
df <- as.data.frame(l)
cols <- paste0(letters, 1:100)
colnames(df) <- cols
df[["c"]] <- 1:100

## Add trace directly here, since plotly adds a blank trace otherwise
p <- plot_ly(df,
      type = "scatter",
      mode = "lines",
      x = ~c, 
      y= ~df[[cols[[1]]]], 
      name = cols[[1]])
## Add arbitrary number of traces
## Ignore first col as it has already been added
for (col in cols[-1]) {
  p <- p %>% add_lines(x = ~c, y = df[[col]], name = col, visible = FALSE)
}

p <- p %>%
    layout(
      title = "Dropdown line plot",
      xaxis = list(title = "x"),
      yaxis = list(title = "y"),
      updatemenus = list(
        list(
            y = 0.7,
            ## Add all buttons at once
            buttons = lapply(cols, function(col) {
              list(method="restyle", 
                args = list("visible", cols == col),
                label = col)
            })
        )
      )
    )

print(p)

不,这就是Shiny的意义-您与R服务器进行了实时会话。 如果您希望将结果完全保存在html文件中,则可能需要预先制作所有图表,然后显示来自markdown文件的结果。 我相信您可以使用bsselectR软件包在markdown中使用下拉菜单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM