Worldphones数据集Shiny App中ggplot条形图无法显示求助
Shiny App ggplot条形图无法显示问题排查
你代码里的核心问题有两个,直接导致条形图无法正常渲染:
- y轴映射错误:你在
ggplot(aes(x = Year, y = input$Users))里用了input$Users,但你的输入控件只有input$Country,根本不存在input$Users这个值,应该映射数据框里的Users列。 - 未过滤用户选择的国家数据:当前代码会把所有国家的电话用户数据都处理,但你需要根据用户选择的国家筛选对应数据,否则要么显示混乱,要么因数据不匹配导致绘图失败。
另外,Year列从行名转换后是字符类型,建议转成数值型,让x轴显示更合理。
修正后的server.R代码
library(datasets) library(tidyverse) library(shiny) # Define a server for the Shiny app function(input, output) { # Fill in the spot we created for a plot output$phonePlot <- renderPlot({ # Render a barplot WorldPhones %>% as.data.frame() %>% rownames_to_column("Year") %>% mutate(Year = as.numeric(Year)) %>% # 把Year转成数值型 pivot_longer(cols = -Year, names_to = "Country", values_to = "Users") %>% filter(Country == input$Country) %>% # 根据用户选择的国家过滤数据 ggplot(aes(x = Year, y = Users)) + # 正确映射y轴为Users列 geom_col(fill = "#2c3e50") + labs(title = paste("电话用户数 -", input$Country), x = "年份", y = "用户数量") + theme_minimal() }) }
ui.R代码可保持不变
library(datasets) library(tidyverse) library(shiny) # Use a fluid Bootstrap layout fluidPage( # Give the page a title titlePanel("Telephones by country"), # Generate a row with a sidebar sidebarLayout( # Define the sidebar with one input sidebarPanel( selectInput("Country", "Country:", choices=colnames(WorldPhones)), ), # Create a spot for the barplot mainPanel( plotOutput("phonePlot") ) ) )
修正后,选择某个国家时会显示对应年份的电话用户数条形图,解决原代码的绘图失败问题。

内容的提问来源于stack exchange,提问作者paolotroia
相关产品推荐
相关产品推荐

