R Shiny Web仪表盘图表无法显示问题排查请求
Shiny图表无法显示的问题修复
问题诊断
原代码存在以下关键问题导致图表无法正常渲染:
- UI代码中混入多余的代码块标记(```),破坏了Shiny UI的语法结构
facet_grid中错误地将列名用引号包裹,导致无法识别数据列- 直方图未指定分箱参数,可能引发渲染警告或异常
- 分类变量未转换为因子,导致图表排序混乱
修复后的完整代码
数据准备与加载
# 下载数据集(本地无文件时执行) if (!file.exists("adult.csv")) { url <- "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DV0151EN-SkillsNetwork/labs/module_4/starter_code/adult.csv" download.file(url, destfile = "adult.csv") } # 加载依赖包 library(shiny) library(dplyr) library(ggplot2) library(ggthemes)
UI代码
ui <- fluidPage( titlePanel("Trends in Demographics and Income"), fluidRow( column(width = 12, wellPanel( selectInput("country", "Native Country", choices = c("United-States", "Canada", "Mexico", "Germany", "Philippines")) ) ) ), fluidRow( column(width = 3, wellPanel( radioButtons("continuous_variable", "Continuous Variable:", choices = c("AGE", "HOURS_PER_WEEK")), radioButtons("graph_type", "Graph Type:", choices = c("Histogram", "Boxplot")) ) ), column(width = 9, plotOutput("p1") ) ), fluidRow( column(width = 3, wellPanel( radioButtons("categorical_variable", "Categorical Variable:", choices = c("EDUCATION","WORKCLASS","SEX")), checkboxInput("is_stacked", "Stacked") ) ), column(width = 9, plotOutput("p2") ) ) )
Server代码
server <- function(input, output) { # 读取数据集并预处理分类变量 adult <- read.csv("adult.csv", stringsAsFactors = FALSE) %>% mutate(across(c(EDUCATION, WORKCLASS, SEX, PREDICTION, NATIVE_COUNTRY), as.factor)) # 按国家筛选的响应式数据 df_country <- reactive({ adult %>% filter(NATIVE_COUNTRY == input$country) }) # 第一个图表渲染 output$p1 <- renderPlot({ p <- ggplot(df_country(), aes_string(x = input$continuous_variable, fill = "PREDICTION")) + facet_grid(. ~ PREDICTION) + theme_minimal() if(input$graph_type == "Histogram") { p + geom_histogram(binwidth = 3, color = "white", alpha = 0.7) } else { p + geom_boxplot(color = "black", alpha = 0.7) } }) # 第二个图表渲染 output$p2 <- renderPlot({ position <- if(input$is_stacked) "stack" else "dodge" ggplot(df_country(), aes_string(x = input$categorical_variable, fill = "PREDICTION")) + facet_grid(. ~ PREDICTION) + geom_bar(position = position, color = "black", alpha = 0.7, width = 0.5) + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) }) } # 运行Shiny应用 shinyApp(ui, server)
关键修复说明
- 移除UI代码中多余的```标记,确保UI结构语法正确
- 修正
facet_grid的列名引用方式,正确识别数据列 - 为直方图添加
binwidth参数,避免自动分箱异常 - 将所有分类变量转换为因子,优化图表排序和显示效果
- 简化位置参数逻辑,提升代码可读性
- 添加主题和坐标轴文本旋转,优化图表视觉体验
内容的提问来源于stack exchange,提问作者Andreas Wisnu Nusantara
相关产品推荐
相关产品推荐

