覆盖ggplot2中的条形图 [英] Overlay bar graphs in ggplot2
问题描述
我试图覆盖 ggplot2
中的条形图我当前的代码会生成一个条形图,但它们堆叠在彼此的顶部。我不希望这样,我希望它们重叠,这样我可以看到每个酒吧高度的差异。
代码:
library(ggplot2)
library(reshape)
x = c(Band 1,Band 2, Band 3)
y1 = c(1,2,3)
y2 = c(2,3,4)
to_plot < - data.frame(x = x,y1 = y1,y2 = y2)
熔化< -melt(to_plot,id =x)
print(ggplot (熔化,aes(x = x,y = value,fill =变量))+ geom_bar(stat =identity,alpha = .3))
堆叠输出:
尝试添加 当我这样做时,我得到: 而且,如下所述,可能 I'm trying to overlay bar graphs in My current code produces a bar plot but they are stacked on top of each other. I dont want this, I would like them overlaid so I can see the differences in each bar height. Code: Stacked output: Try adding When I do that, I get: And, as noted below, probably 这篇关于覆盖ggplot2中的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! position =identity code>到你的
geom_bar
调用。你会从?geom_bar
注意到,默认位置是 stack
,这是你在这里看到的行为。 / p>
print(ggplot(融化,aes(x = x,y = value,fill = variable))+
geom_bar(stat =identity,position =identity,alpha = .3))
position =dodge
会是更好的选择:
ggplot2
library(ggplot2)
library(reshape)
x = c("Band 1", "Band 2", "Band 3")
y1 = c("1","2","3")
y2 = c("2","3","4")
to_plot <- data.frame(x=x,y1=y1,y2=y2)
melted<-melt(to_plot, id="x")
print(ggplot(melted,aes(x=x,y=value,fill=variable)) + geom_bar(stat="identity", alpha=.3))
position = "identity"
to your geom_bar
call. You'll note from ?geom_bar
that the default position is stack
which is the behavior you're seeing here.print(ggplot(melted,aes(x=x,y=value,fill=variable)) +
geom_bar(stat="identity",position = "identity", alpha=.3))
position = "dodge"
would be a nicer alternative: