如何用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

