You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny中如何将响应式输入input$measurement用作绘图Y轴?

问题解决:动态切换Shiny ggplot的Y轴

修正后的完整代码

library(dplyr)
library(ggplot2)
library(shiny)
library(shinyWidgets)

mtcars$cars <- rownames(mtcars)
# 移除非数值型的"cars"列,避免无效选项
available_measurements <- setdiff(colnames(mtcars), "cars")

ui <- fluidPage(
  titlePanel("Car comparisons"),
  selectInput("measurement", "Select Measurement", choices = available_measurements, selected = "mpg"),
  selectInput("car", "Select Car", choices = mtcars$cars, multiple=TRUE),
  plotOutput("plot")
)

server <- function(input, output, session) {
  
  filtered_data <- reactive({
    req(input$car)
    mtcars %>%
      filter(cars %in% input$car)
  })
  
  output$plot <- renderPlot({
    req(filtered_data(), input$measurement)
    
    ggplot(filtered_data(), aes(x = cars, y = .data[[input$measurement]])) +
      geom_bar(stat = "identity", fill = "pink") +
      labs(y = input$measurement) +
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
  })
}

shinyApp(ui = ui, server = server)

关键修改说明

  • 修正数据源筛选:原代码中input$measurement %in% c是无效过滤条件,直接移除,仅保留按选中车型筛选的逻辑,同时用req()确保输入有效后再执行计算。
  • 优化可选指标列表:移除列名里的cars,避免用户选择非数值型的车型列作为Y轴。
  • 动态指定Y轴:在aes()中用.data[[input$measurement]]动态引用选中的列,这是dplyr/ggplot2推荐的安全动态列引用方式。
  • 修复绘图逻辑:移除多余的lapply,直接基于筛选后的数据集绘图,指定X轴为车型、Y轴为选中指标,同时添加坐标轴标签和X轴文本倾斜优化,提升可读性。

内容的提问来源于stack exchange,提问作者bi0haz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:15:48