如上所述,这是我之前答案here的副本.
然而,@YBS的方法过于复杂,我想提供直接比较的可能性.对于ggplot
或plotly
,最好使用长格式的data.frame
(例如,使用data.table::melt
从宽转换为长).这样,我们可以使用plot_ly
的split
、name
或color
参数基于数据创建多条记录道:
library(shiny)
library(shinydashboard)
library(plotly)
library(gapminder)
DF <- gapminder[, c(1, 3, 4)]
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
selectizeInput(
"col",
"Pick a column for y-axis to plot, if ticked in checkbox below",
choices = NULL,
selected = NULL,
multiple = TRUE
),
checkboxGroupInput("chk", "Display Plot", choices = DF$country[1])
),
dashboardBody(tabsetPanel(id = "tabs",
tabPanel(
"Plot data" , plotlyOutput("tseries")
)))
)
server <- function(input, output, session) {
freezeReactiveValue(input, "col")
# server-side selectize for improved performance
updateSelectizeInput(
session,
"col",
choices = DF$country,
selected = DF$country[1],
server = TRUE
)
observeEvent(input$col, {
updateCheckboxGroupInput(
session,
"chk",
"Select item to plot",
choices = input$col,
selected = input$col
)
})
output$tseries <- renderPlotly({
if (is.null(input$chk)) {
plotly_empty(type = 'scatter', mode = 'lines')
} else {
plot_ly(
DF[DF$country %in% input$chk, ],
type = 'scatter',
mode = 'lines',
x = ~ year,
y = ~ lifeExp,
split = ~ country
)
}
})
}
shinyApp(ui, server)