繁体   English   中英

R ggplot2堆叠条形图,定义条形颜色

[英]R ggplot2 stacked barplot, defining bar colors

我离我要达到的目标非常接近,但是找不到增加画龙点睛的方法。 这就是我所拥有的,使用foo数据和代码来生成图形。
重塑包中的融化数据:

mdf <- structure(list(v1 = structure(c(1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L), .Label = c("ind1", 
"ind10", "ind2", "ind3", "ind4", "ind5", "ind6", "ind7", "ind8", 
"ind9"), class = "factor"), v2 = c(2, 3, 1, 2, 2, 2, 3, 1, 4, 
4, 2, 3, 1, 2, 2, 2, 3, 1, 4, 4), variable = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L), .Label = c("v3", "v4"), class = "factor"), value = c(0.8, 
0.7, 0.7, 0.6, 0.4, 0.3, 0.2, 0.3, 0.9, 0.8, 0.2, 0.3, 0.3, 0.4, 
0.6, 0.7, 0.8, 0.7, 0.1, 0.2)), .Names = c("v1", "v2", "variable", 
"value"), row.names = c(NA, -20L), class = "data.frame")

图表:

library(ggplot2)
ggplot(mdf,aes(x=reorder(v1,v2),y=value,fill=factor(v2))) + geom_bar(stat="identity",color="black")

在此处输入图片说明 现在,我需要为每个条形图的顶部堆栈进行不同的着色,例如用一些透明性或事件颜色将顶部的所有堆栈变为灰色。 我可以使用数据集的当前结构来执行此操作,还是应该考虑以其他方式重塑数据?

谢谢

编辑:从Didzis提供的代码输出图形: 在此处输入图片说明

我建议两次使用geom_bar() -首先,绘制所有数据并设置fill="grey"然后在第二个geom_bar()仅使用variablev3 (底部栏)的数据子集,对于那些使用fill=v2

ggplot(mdf,aes(x=reorder(v1,v2),y=value)) + 
        geom_bar(stat="identity",color="black",fill="grey")+
        geom_bar(data=subset(mdf,variable=="v3"),
              aes(x=reorder(v1,v2),y=value,fill=factor(v2)),
               stat="identity",color="black")

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM