[英]R Shiny to select traces for Plotly line chart?
我正在尝试使用 Shiny 来选择我想在使用 Plotly 呈现的多折线图中绘制的变量。 我有很多变量,所以我想使用 Shiny 进行选择,而不是使用 Plotly 的交互式图例“单击”选择机制。 示例数据:
library(plotly)
# Example dataframe
foo <-data.frame( mon = c("Jan", "Feb", "Mar"),
var_1 = c(100, 200, 300),
var_b = c(80, 250, 280),
var_three = c(150, 120,201)
)
直接使用 Plotly 时,我可以使用如下代码手动添加跟踪:
p <- plot_ly(x = foo$mon, y = foo$var_1, line = list(shape="linear"))
p <- add_trace(p, x = foo$mon, y = foo$var_b)
p <- add_trace(p, x = foo$mon, y = foo$var_three)
print(p)
现在我想使用 Shiny 复选框来选择我希望在图中看到的变量。 选择在 input$show_vars 中捕获,但我如何循环并绘制这个不断变化的变量列表? 这是我的 app.R 代码,它手动绘制了其中一个变量。 建议表示赞赏!
#------------------------------------------------------------------------------
# UI
#------------------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
checkboxGroupInput('show_vars', 'Columns in the dataset', names(foo),
selected = c('mon', 'var_1')),
helpText('Select the variables to show in the graph.')
),
mainPanel(
plotlyOutput("myPlot")
)
)
)
#------------------------------------------------------------------------------
# SERVER
# Need to loop through input$show_vars to show a trace for each one?
#------------------------------------------------------------------------------
server <- function(input, output) {
# a large table, reative to input$show_vars
output$uteTable = renderDataTable({
library(ggplot2)
ute[, input$show_vars, drop = FALSE]
})
output$myPlot = renderPlotly({
plot_ly(x=foo$mon, y=foo$var_1, line = list(shape="linear"))
## How to add the other traces selected in input$show_vars??
})
}
shinyApp(ui = ui, server = server)
更新:我现在意识到我需要脚本来避免硬编码第一个图以使用 foo$var_1。 该图应使用复选框中的任何可能选项(减去 $mon,我已从选择列表中删除了它)。 当我尝试使第一个情节语句有条件时,我收到消息“错误:最后一个情节不存在”。 即,这不起作用:
output$myPlot = renderPlotly({
# p <- plot_ly(x=foo$mon, y=foo$var_1, line = list(shape="linear"))
for (item in input$show_vars) {
if (item == 1){
p <- plot_ly(x=foo$mon, y=foo[[item]], line = list(shape="linear"))
}
if(item > 1){
p <- add_trace(p, x = foo$mon, y = foo[[item]], evaluate = TRUE)
}
}
print(p)
看看这是不是你想要的。 此外,您可能希望删除 checkboxGroup 中的前两项,以便它们不可移动(取决于您想要的内容)。
output$myPlot = renderPlotly({
p <- plot_ly(x=foo$mon, y=foo$var_1, line = list(shape="linear"))
## How to add the other traces selected in input$show_vars??
for (item in input$show_vars) {
p <- add_trace(p, x = foo$mon, y = foo[[item]], evaluate = TRUE)
}
print(p)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.