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

如何用ggplot2按AGEGRP因子绘制多箱线图?技术求助

Great catch on needing to convert AGEGRP to a factor—you’re absolutely right about that being a key issue here! Let’s break down what’s going wrong and fix your code step by step:

1. Fix the syntax error first

Your code has a double + right before geom_boxplot—that’s a simple syntax mistake that will throw an error immediately. Remove one of those plus signs to get past the first hurdle.

2. Convert AGEGRP to a factor (the core fix)

Since AGEGRP is read in as a numeric variable by default, ggplot treats it as a continuous axis. That means it won’t create separate boxplots for each age group (it’ll try to plot all data against a single continuous x-scale instead). We can fix this in two ways:

Option A: Transform the column in your data frame

This makes the factor conversion permanent for your popSample dataset:

library(tidyverse)

popSample <- read.csv("./datafiles/cc-est2018-alldata.csv") %>%
  select(STNAME, CTYNAME, YEAR, AGEGRP, TOT_POP, TOT_MALE, TOT_FEMALE) %>%
  mutate(AGEGRP = factor(AGEGRP))  # Convert to factor here

Option B: Convert directly in the aes() call

If you don’t want to modify the original data frame, you can handle the conversion on the fly when defining the plot:

# No need to mutate the data frame first
ageGroups <- ggplot(popSample, aes(x = factor(AGEGRP), y = TOT_POP)) +
  # rest of your code...

3. Correct your axis labels

Your labs() call has the x and y axes reversed: your x-axis should represent "Age Groups" (since it’s AGEGRP) and the y-axis should show "Total Population" (since it’s TOT_POP).

Full working code

Here’s the polished, error-free version using Option A:

library(tidyverse)

# Read, clean, and prepare data
popSample <- read.csv("./datafiles/cc-est2018-alldata.csv") %>%
  select(STNAME, CTYNAME, YEAR, AGEGRP, TOT_POP, TOT_MALE, TOT_FEMALE) %>%
  mutate(AGEGRP = factor(AGEGRP))

# Create the multi-boxplot
ageGroups <- ggplot(popSample, aes(x = AGEGRP, y = TOT_POP)) +
  geom_boxplot(fill = "red", alpha = 0.5, color = "darkred") +
  labs(title = "Population Distribution by Age Group",
       x = "Age Group",
       y = "Total Population") +
  theme_light()

# Display the plot
ageGroups

Bonus: Make labels more readable (optional)

If you want to replace the numeric codes (like "0") with descriptive labels (like "All Ages"), you can use fct_recode() to update the factor levels:

popSample <- popSample %>%
  mutate(AGEGRP = fct_recode(factor(AGEGRP),
                             "All Ages" = "0",
                             "1-4 Years" = "1",
                             "5-9 Years" = "2",
                             # Add mappings for groups 3-18 as needed
                             ))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:54:09