2014-11-13 37 views
-1

这是基于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)) 

注意,Specie变量是跨yz相同。

我可以创建分别为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

这是怎么回事,如果你rbind的数据,并使用源指标变量更容易。 –

+1

另一个以'ggplot'开头的好资源:[Cookbook For R:条形图和折线图](http://www.cookbook-r.com/Graphs/Bar_and_line_graphs_(ggplot2)/) – Gregor

回答

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