如何在ggplot条形图中单独修改Savona城市的条形颜色?
自定义ggplot条形图中指定城市的条形颜色
问题描述
使用ggplot绘制条形图时,希望将城市Savona对应的两个条形分别改为红色和蓝色,其余城市的条形保持原有填充样式。原代码如下:
ggplot(aes(fill=name, x= `City Name`, y = value)) + geom_bar(position="dodge", stat="identity", width = 0.7)+ theme_classic()+ scale_y_continuous(breaks = seq(0,100, 5))+ geom_text(aes(label = paste0(format(pcty),"%"), y = pcty), hjust= 0, vjust= 1.5, size = 3.5, colour = "black")+ scale_x_discrete(guide = guide_axis(n.dodge = 2)) + theme(legend.position = "none", axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text = element_text(face="bold"))
解决方案
核心思路是通过scale_fill_manual()自定义填充颜色,针对Savona城市的两个name类别单独指定颜色,其余类别保留默认配色。具体修改后的完整代码如下:
# 假设你的数据框名为df,请替换为实际数据框名称 default_colors <- scales::hue_pal()(length(unique(df$name))) names(default_colors) <- unique(df$name) # 替换Savona对应的两个name的颜色(可根据实际name值直接指定,比如"Category1") savona_names <- unique(df$name[df$`City Name` == "Savona"]) default_colors[savona_names[1]] <- "red" default_colors[savona_names[2]] <- "blue" ggplot(df, aes(fill=name, x= `City Name`, y = value)) + geom_bar(position="dodge", stat="identity", width = 0.7)+ theme_classic()+ scale_y_continuous(breaks = seq(0,100, 5))+ geom_text(aes(label = paste0(format(pcty),"%"), y = pcty), hjust= 0, vjust= 1.5, size = 3.5, colour = "black")+ scale_x_discrete(guide = guide_axis(n.dodge = 2)) + # 应用自定义填充颜色 scale_fill_manual(values = default_colors) + theme(legend.position = "none", axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text = element_text(face="bold"))
关键说明
scales::hue_pal()会生成和ggplot默认一致的配色,确保其余城市的条形颜色与原图表完全匹配- 如果明确知道Savona对应的两个
name具体值,可直接替换代码中的savona_names部分,比如default_colors["Online"] <- "red",这样更精准
内容的提问来源于stack exchange,提问作者io_boh
相关产品推荐
相关产品推荐

