修改ggplot中geom_bar默认填充色时遇报错问题咨询
scale_fill_manual() Hey Tyler, let's break down why you're hitting that error when customizing your bar plot's fill colors. The good news is since your plot works fine without scale_fill_manual(), the issue is almost certainly a syntax misstep in how you're defining the fill scale—not a problem with your Accident_severity_combined variable itself.
Here are the most common fixes to try:
1. Correct the values Parameter Syntax
This is the #1 cause of this error. You need to explicitly assign your color palette to the values argument inside scale_fill_manual(). It's easy to forget this and pass colors directly, which confuses ggplot's internal functions.
Wrong (causes your error):
p <- ggplot(uk, aes(x = Road_Type, fill = Accident_severity_combined)) + geom_bar() + scale_fill_manual("Accident Severity", "red", "orange", "green") # No `values=`!
Right:
p <- ggplot(uk, aes(x = Road_Type, fill = Accident_severity_combined)) + geom_bar() + scale_fill_manual( name = "Accident Severity", # Optional: Custom legend title values = c("red", "orange", "green") # Colors mapped to your severity levels )
2. Match Color Count to Factor Levels
If Accident_severity_combined is a factor (which it should be for consistent color mapping), make sure your color vector has exactly as many entries as there are factor levels. Run this to check:
levels(uk$Accident_severity_combined)
For more control, you can map specific colors to specific severity levels by naming the color vector:
p <- ggplot(uk, aes(x = Road_Type, fill = Accident_severity_combined)) + geom_bar() + scale_fill_manual( name = "Accident Severity", values = c( "Fatal" = "#d73027", "Serious" = "#fc8d59", "Slight" = "#fee090" ) )
3. Convert Character Columns to Factors (If Needed)
If Accident_severity_combined is stored as a character column, convert it to a factor first to ensure color mapping stays consistent (even if your data order changes):
uk$Accident_severity_combined <- factor(uk$Accident_severity_combined, levels = c("Fatal", "Serious", "Slight"))
Try these steps, and your custom fill colors should load without the error!
内容的提问来源于stack exchange,提问作者Tyler

