[英]Stacked Barplot in R with ggplot2
I have got a question about creating a stacked barplot in R with ggplot2. 我有一个关于使用ggplot2在R中创建堆叠式barplot的问题。 What I want to create is a stacked bar plot in which every bar is placed "on top" of the other.
我要创建的是一个堆积的条形图,其中每个条形图都放置在另一个条形图的“顶部”。
x = c(100,200,400,600,800,1000,1250,1500)
y1 = c(1,2,3,4,5,6,7,8)
y2 = c(8,7,6,5,4,3,2,1)
data <- data.frame(x,y1,y2)
ggplot(data, aes(x, y1,label=x)) +
geom_bar(stat="identity", fill="blue", position="stack") +
geom_bar(stat="identity",aes(x, y2), fill="orange", position="stack")
What I get now are stacked bars. 我现在得到的是堆积的酒吧。 But for x = 100 I get one bar from 0 - 1 and a second from 0 - 8. But what I want to get is one from 0 - 1 and a second from 1 - 9.
但是对于x = 100,我从0-1得到一个小节,从0-8中得到一个小节。但是我想要得到的是从0-1中得到一个小节,从1-9中得到一个小节。
Have you an idea how I can solve this problem (without summing up the inputs manually)? 您是否知道如何解决此问题(无需手动汇总输入)?
Thanks for your help! 谢谢你的帮助!
Try: 尝试:
ggplot(melt(data, id='x')) + geom_bar(aes(x=x, y=value, fill=variable), stat='identity')
How about: 怎么样:
df <- data.frame(x = c(x,x), y = c(y1, y2), grp = factor(rep(c("Grp 1", "Grp 2"), each = 8)))
ggplot(df, aes(x, y, fill = grp)) + geom_bar(stat = "identity", position="stack")
Use scale_fill_manual
if you want to tweak the colors. 如果要调整颜色,请使用
scale_fill_manual
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.