使用geom_errorbar重排序因子水平时颜色不匹配问题求助
问题:ggplot2中误差棒颜色无法匹配指定值(已重排x轴因子)
需要绘制带误差棒的柱状图,已重排x轴因子水平,柱状图位置和颜色正确,但误差棒颜色始终无法匹配预设的vals颜色配置,尝试两种代码均无效:
无效代码1
xx<-c("one", "two", "three", "four", "five") yy<-c(4, 6, 8, 10, 12) zz<-c(0.5, 1, 2, 4, 5) add<-data.frame(xx, yy, zz) add$xx<-factor(add$xx, levels =c("five", "three", "two", "one", "four")) vals<-c("five"= "white", "three"="blue", "two"= "green", "one"= "orange", "four"= "black") vals2<-c("five"= "white", "three"="white", "two"= "white", "one"= "black", "four"= "black") graph1<-ggplot(data= add, aes(x=xx, y= yy, fill = xx))+ geom_bar(stat = "identity")+ geom_errorbar(aes(ymin=yy-zz, ymax=yy+zz, color=vals))+ scale_color_manual(values=vals, limits = c("five","three","two", "one", "four"), guide="none")+ scale_fill_manual(values=vals2, guide = "none") graph1
生成效果:
无效代码2
graph2<-ggplot(data= add, aes(x=xx, y= yy, fill = xx))+ geom_bar(stat = "identity")+ geom_errorbar(aes(ymin=yy-zz, ymax=yy+zz), color=c("white", "blue", "green", "orange", "black"))+ scale_fill_manual(values=vals2, guide = "none") graph2
生成效果:
解决方案
核心问题是误差棒的颜色映射没有和x轴的因子水平正确绑定,正确做法是将color映射到xx因子,再通过scale_color_manual指定对应颜色:
xx<-c("one", "two", "three", "four", "five") yy<-c(4, 6, 8, 10, 12) zz<-c(0.5, 1, 2, 4, 5) add<-data.frame(xx, yy, zz) add$xx<-factor(add$xx, levels =c("five", "three", "two", "one", "four")) vals<-c("five"= "white", "three"="blue", "two"= "green", "one"= "orange", "four"= "black") vals2<-c("five"= "white", "three"="white", "two"= "white", "one"= "black", "four"= "black") # 正确代码 graph_correct<-ggplot(data= add, aes(x=xx, y= yy, fill = xx))+ geom_bar(stat = "identity")+ # 将color映射到xx,让每个因子水平对应颜色 geom_errorbar(aes(ymin=yy-zz, ymax=yy+zz, color = xx))+ # 用vals指定每个xx水平对应的颜色,和fill的scale逻辑一致 scale_color_manual(values=vals, guide="none")+ scale_fill_manual(values=vals2, guide = "none") graph_correct
错误原因解释
- 代码1中直接在
aes里写color=vals,相当于给每个误差棒都传递了完整的颜色向量,ggplot无法正确匹配到单个因子水平; - 代码2中直接传入
color向量,ggplot会按数据框的行顺序分配颜色,但数据框行顺序和xx因子重排后的x轴显示顺序不一致,导致颜色错位。
内容的提问来源于stack exchange,提问作者Crobatic
相关产品推荐
相关产品推荐

