Shiny中用selectInput修改ggplot的x与fill变量时y轴不显示count的问题
解决Shiny仪表盘ggplot Y轴不显示count的问题
嘿,我一眼就看出问题所在啦!你遇到的Y轴不显示count值的核心原因是:ggplot的aes()函数默认会把input$x这类字符串当成字面量,而不是数据框里的变量。这样一来,ggplot会把整个input$x的字符串当成一个单独的x类别,自然只会统计出1个count,Y轴就不会正常显示你想要的数值了。
给你两个靠谱的解决方案,推荐第一个:
方案1:使用.data代词(ggplot官方推荐)
这是现在最规范的处理方式,能安全地引用字符串形式的变量名:
inputPanel( selectInput('x', 'X', names(data)), selectInput('fill_var', 'Fill Variable', names(data)) # 把y改成fill_var更清晰,避免和Y轴混淆 ) renderPlot({ ggplot(data, aes(x = .data[[input$x]])) + geom_bar(aes(fill = .data[[input$fill_var]]), position = position_stack()) })
方案2:使用aes_string(已弃用但仍可用)
这个方法是旧版本的处理方式,现在官方更推荐.data的写法,但如果你需要兼容老代码也可以用:
inputPanel( selectInput('x', 'X', names(data)), selectInput('fill_var', 'Fill Variable', names(data)) ) renderPlot({ ggplot(data, aes_string(x = input$x)) + geom_bar(aes_string(fill = input$fill_var), position = position_stack()) })
额外提示
- 我把原来的
selectInput('y', 'Y', names(data))改成了fill_var,这样变量名更直观,避免和geom_bar默认的Y轴(count)混淆,你可以根据自己的习惯调整。 - 如果你需要自定义Y轴标签,可以加上
ylab("Count")来明确显示。
内容的提问来源于stack exchange,提问作者Thomas Kidd
相关产品推荐
相关产品推荐

