R语言Shiny仪表盘动态绘制多国家多变量时序图问题求助
解决方案
错误原因
more than one expression parsed报错的核心是aes_string()的y参数仅支持传入单个变量名,当你选择多个变量时input$myvariable为长度大于1的字符向量,直接传入会触发解析错误。
实现思路
无需硬编码任何变量/国家名称,将筛选后的宽表数据转换为长表结构,把所有选中的变量收拢为「变量名-数值」的键值对,再通过ggplot的美学映射即可实现多国家多变量同时绘图。
修改后完整可运行代码
library(shiny) library(shinyWidgets) library(dplyr) library(tidyverse) library(scales) df = data.frame("Country" = c("USA","USA","USA","USA","AFG","AFG","AFG","AFG"), "Year" = c(2000,2001,2002,2003,2000,2001,2002,2003), "Variable_1" = c(10,12,14,16,10,11,12,13), "Variable_2" = c(20,19,18,17,20,21,22,23), "Variable_3" = c(13,13,14,14,16,16,12,12)) ui = fluidPage( titlePanel("My Dashboard"), pickerInput("myvariable","Pick variables", choices =c("Variable_1","Variable_2","Variable_3"), options =list("actions-box" = TRUE), multiple=TRUE, selected = "Variable_1"), sliderInput("year_selector", "Select Year Range",min = 2000,max = 2003,value = c(2000, 2003)), pickerInput("choicePicker","Pick countries",choices =c("USA", "AFG"), options =list("actions-box" = TRUE), multiple=TRUE, selected="USA"), plotOutput("trend") ) server = function(input, output, session){ # 筛选基础数据 selected <- reactive({ filter(df, Country %in% input$choicePicker, Year>=input$year_selector[1], Year<=input$year_selector[2]) }) # 转为长表,适配多变量绘图 selected_long <- reactive({ selected() %>% pivot_longer(cols = all_of(input$myvariable), names_to = "variable", values_to = "value") }) output$trend = renderPlot({ ggplot(selected_long(), aes(x=Year, y=value, color=Country, linetype=variable, group=interaction(Country, variable))) + geom_line(size = 2) + scale_x_continuous(breaks = pretty_breaks()) + labs(x = "年份", y = "数值", title = "多国家多变量趋势图") + theme(legend.position = "bottom") }) } shinyApp(ui=ui, server=server)
可选优化
如果希望不同变量分开展示,仅需在ggplot代码末尾添加facet_wrap(~variable),即可自动按选中的变量生成独立子图,无需硬编码变量名称。
内容的提问来源于stack exchange,提问作者thehand0
相关产品推荐
相关产品推荐

