ggplot绘制多色柱状图时scale_fill_manual等配色函数失效求助
问题原因
你没有在图形的美学映射(aes)中绑定fill(填充)对应的分组变量,scale_fill_*系列函数找不到可以匹配的填充维度,因此设置的色值不会生效。
修复方案
在ggplot的全局美学参数或者geom_bar的美学参数中,新增fill映射,绑定你要用来区分颜色的分组字段即可,这里你是要按X轴的分类变量区分颜色,直接把该字段赋值给fill就行。
修改后完整代码
ggplot(data=sust_future, aes(x=as.factor(`sust.self-perception`), fill = as.factor(`sust.self-perception`))) + geom_bar(aes(y = (..count..)/sum(..count..)), width=0.6) + scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9")) + scale_y_continuous(labels=scales::percent) + labs(title = "xxx", x = "", y = "") + theme(legend.position = "bottom", axis.text.x=element_text(size=8), axis.text.y=element_text(size=8))
补充说明
- 如果不需要显示图例,可以在
scale_fill_manual中加参数guide = "none",或者把theme里的legend.position设置为"none"。 - 如果
sust.self-perception的分类数量不是3个,需要对应调整scale_fill_manual的values参数里的颜色数量,避免出现长度不匹配的警告。

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

