【发布时间】:2016-08-16 10:34:39
【问题描述】:
我正在尝试使用 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)
【问题讨论】: