条形图中的并排条形图

时间:2014-11-13 19:07:30

标签: r plot ggplot2

这基于this post。假设我有这些数据:

y = data.frame(Specie=c('A','V','R','P','O'),Number=c(18756,8608,3350,3312,1627))
z = data.frame(Specie=c('A','V','R','P','O'),Number=c(17000,1000,8000,5500,9000))

请注意,Speciey z变量相同。

我可以通过以下方式分别为y和z创建条形图:

library(ggplot2)
qplot(x=y[,1], y=y[,2], geom="bar", stat="identity")
qplot(x=z[,1], y=z[,2], geom="bar", stat="identity")

我如何将这两个图合并为一个?我们的想法是让yz条彼此相邻,都在同一个关联的Specie变量中。 x的条形,例如,蓝色,y的条形,例如,红色。

1 个答案:

答案 0 :(得分:1)

y = data.frame(Specie=c('A','V','R','P','O'),Number=c(18756,8608,3350,3312,1627))
z = data.frame(Specie=c('A','V','R','P','O'),Number=c(17000,1000,8000,5500,9000))

library("ggplot2")
library("reshape2")

df=merge(y,z,by=c("Specie"))
names(df)=c("Specie","y","z")

df=melt(df)

ggplot(df,aes(x=Specie,y=value,fill=variable))+geom_bar( stat="identity",position=position_dodge())

enter image description here