R Shiny实现按值排序Top3柱状图的问题排查
R Shiny plotly柱状图排序及Top3展示问题修复
问题描述
我是编程新手,对R语言的掌握尤其薄弱。现有一个数据框,希望通过柱状图展示按数值从大到小排序的Top3数据,此前尝试编写的多版代码都无法生成符合预期的图表,以下是我最新的实现代码:
library(shiny) library(plotly) my_data <- data.frame(x1 = c("a","b", "c","d","e","f","g","h"), x2 = c(200, 200, 100,200,200,100,200,100), x3 = c(100,400,500,50,100,300,100,50)) df1 <- my_data[order(my_data$x3),] #order by x3 value, to create rank ui <- tabPanel("Test", sidebarLayout( sidebarPanel( selectInput(inputId = "why", label = "1. Select", choices = df1$x2), ), mainPanel(plotlyOutput("test")) )) server <- function(input, output, session) { output$test <- renderPlotly({ df2 <- df1 %>% filter(x2 ==input$why) #filter by x2 p <-ggplot(df2, aes(x = x1, y=x3)) + geom_bar(stat = "identity") fig <- ggplotly(p) fig })} shinyApp(ui = ui, server = server)
现存问题
- 运行代码生成的柱状图无法按照
x3字段的值正确排序 - 未实现筛选后仅展示Top3条目的需求
- 下拉选择框存在重复选项
- 代码使用了管道符
%>%但未加载对应依赖包,直接运行会报错
问题原因
- ggplot绘制分类轴时,默认会将字符型分类变量按字母顺序排列,不会自动关联y轴数值调整顺序,全局预排序的数据集无法直接控制ggplot的轴展示顺序
- 数据筛选环节没有做降序排序、截取Top3的操作
selectInput选项直接取了x2字段全量值,没有做去重处理
修正后完整代码
library(shiny) library(plotly) library(dplyr) library(ggplot2) my_data <- data.frame(x1 = c("a","b", "c","d","e","f","g","h"), x2 = c(200, 200, 100,200,200,100,200,100), x3 = c(100,400,500,50,100,300,100,50)) ui <- tabPanel("Test", sidebarLayout( sidebarPanel( selectInput(inputId = "why", label = "1. Select", choices = unique(my_data$x2)), ), mainPanel(plotlyOutput("test")) )) server <- function(input, output, session) { output$test <- renderPlotly({ df2 <- my_data %>% filter(x2 == input$why) %>% arrange(desc(x3)) %>% slice_head(n = 3) %>% mutate(x1 = factor(x1, levels = x1)) p <- ggplot(df2, aes(x = x1, y = x3)) + geom_bar(stat = "identity", fill = "#1f77b4") + labs(x = "类别", y = "x3数值") fig <- ggplotly(p) fig })} shinyApp(ui = ui, server = server)
关键修改点
- 补充加载缺失的
dplyr、ggplot2依赖包 - 下拉选择框选项用
unique()去重,避免重复选项 - 数据筛选后增加
arrange(desc(x3))做降序排序,再用slice_head(n=3)截取Top3条目 - 对分类变量
x1做因子水平绑定,将因子顺序和排序后的x1顺序对齐,彻底解决柱状图排序错乱问题
内容的提问来源于stack exchange,提问作者Erwin Hidayat
相关产品推荐
相关产品推荐

