[英]R ggplot2 stacked barplot, defining bar colors
I'm very close to what I want to achieve but can't find a way to add the finishing touch to my graph. 我离我要达到的目标非常接近,但是找不到增加画龙点睛的方法。 Here's what I have, with foo data and code to produce the graph.
这就是我所拥有的,使用foo数据和代码来生成图形。
Melted data from the reshape package: 重塑包中的融化数据:
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")
Graph : 图表:
library(ggplot2)
ggplot(mdf,aes(x=reorder(v1,v2),y=value,fill=factor(v2))) + geom_bar(stat="identity",color="black")
Now I need to color the top stack of each bar differently, say with some transparency or event color all the top stack grey.
现在,我需要为每个条形图的顶部堆栈进行不同的着色,例如用一些透明性或事件颜色将顶部的所有堆栈变为灰色。 Can I do that with the current structure of my data set or should I consider reshaping my data differently ?
我可以使用数据集的当前结构来执行此操作,还是应该考虑以其他方式重塑数据?
Thanks 谢谢
EDIT : output graph from the code provided by Didzis : 编辑:从Didzis提供的代码输出图形:
I would suggest to use geom_bar()
twice - first, plot all data and set fill="grey"
then in second geom_bar()
use only subset of data where variable
is v3
(bottom bars) and for those use fill=v2
. 我建议两次使用
geom_bar()
-首先,绘制所有数据并设置fill="grey"
然后在第二个geom_bar()
仅使用variable
为v3
(底部栏)的数据子集,对于那些使用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.