Shiny中实现可选择变量的双柱状图绘制及标签动态更新
解决Shiny动态双柱状图筛选与图例更新问题
问题需求
需要实现:
- X轴为国家,每个国家展示固定的
x54(平均月薪)和通过下拉框选择的x48/x49(不同位置的单间房租)双柱形 - 图例标签根据所选变量自动切换对应描述
修改后的完整代码
library(shiny) library(ggplot2) library(tidyverse) # 加载数据集(可替换为你的本地读取代码) df <- structure(list( country = c("Andorra", "Austria", "Belgium", "Denmark", "Finland", "France", "Germany", "Greece"), x48 = c(811.73, 710.0385, 765.8359, 961.434, 701.9176, 716.7308, 701.6187, 468.1942), x49 = c(655.2433, 607.8058, 628.3675, 692.426, 575.4287, 587.7711, 544.2052, 370.2103), x54 = c(2801.597, 2224.757, 2320.216, 3130.023, 2582.625, 2399.011, 2621.368, 804.5603) ), class = "data.frame", row.names = c(NA, -8L)) ui = fluidPage( titlePanel("Salary vs. Rent Comparison"), sidebarLayout( sidebarPanel( # 下拉框显示友好标签,传递对应变量名 selectInput("x1", "Type of house rent:", choices = c("x48" = "1 room in the center", "x49" = "1 room outside the center"), selected = "x48") ), mainPanel( plotOutput("plot") ) ) ) server = function(input, output) { output$plot <- renderPlot({ # 变量-标签映射表 label_map <- c( "x48" = "1 room in the center", "x49" = "1 room outside the center", "x54" = "Average Monthly Salary" ) # 变量-颜色映射表,保证颜色一致性 color_map <- c( "x48" = "#DA560A", "x49" = "#DA560A", "x54" = "#58C114" ) df_long <- df %>% pivot_longer(-country) ggplot(data = df_long %>% filter(name %in% c(input$x1, "x54")), aes(x = country, y = value, fill = factor(name))) + geom_col(position = position_dodge(width = 0.8)) + # 动态匹配标签和颜色,不受数据顺序影响 scale_fill_manual(values = color_map, labels = label_map, name = "Metric") + theme_light() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) + labs(x= "Country", y= "USD") }) } # 运行应用 shinyApp(ui, server)
核心修改说明
下拉框逻辑优化:
- 仅提供
x48/x49作为可选选项,避免选中x54导致重复展示;同时用命名向量让用户看到友好标签,后台传递变量名。
- 仅提供
动态筛选与标签更新:
- 通过
filter(name %in% c(input$x1, "x54"))实现固定展示x54+动态选择房租变量的逻辑。 - 用
label_map命名向量绑定变量名和对应描述,确保图例标签随选择自动切换。
- 通过
颜色一致性保障:
- 用
color_map命名向量指定每个变量的颜色,不管选择哪个房租变量,房租柱形颜色统一,月薪柱形颜色固定,避免数据顺序变化导致颜色错乱。
- 用
细节调整:
- 调整
position_dodge宽度优化柱形间距;修改X轴文本对齐方式,避免文字重叠。
- 调整
内容的提问来源于stack exchange,提问作者walter
相关产品推荐
相关产品推荐

