我想制作一个简单的销售报告折线图,显示从下拉菜单中给定产品的产品销售额。我使用情节和闪亮的方式做了一个报告,但我无法找到与同事分享报告的方法,而无需使用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的行。
虽然选择c3显示a1的行,d4代表b2,等等。看起来顺序是shiftet 2列。
答案 0 :(得分:2)
以下示例完全符合您的要求,可以嵌入到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)
答案 1 :(得分:1)
不,这就是Shiny的观点 - 你有一个与R服务器的实时会话。如果您想将结果完全放在html文件中,您可能想要预先制作所有图表,然后显示降价文件的结果。我相信您可以使用bsselectR
包在markdown中使用下拉菜单。