覆盖ggplot2中的条形图 [英] Overlay bar graphs in ggplot2

查看:162
本文介绍了覆盖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))

堆叠输出:

解决方案

尝试添加 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会是更好的选择:




I'm trying to overlay bar graphs in ggplot2

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:

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))

Stacked output:

解决方案

Try adding 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.

When I do that, I get:

print(ggplot(melted,aes(x=x,y=value,fill=variable)) + 
        geom_bar(stat="identity",position = "identity", alpha=.3))

And, as noted below, probably position = "dodge" would be a nicer alternative:

这篇关于覆盖ggplot2中的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆