条形图中的并排条形图 [英] Side-by-side bars in bar plot

查看:150
本文介绍了条形图中的并排条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是基于这篇文章。假设我有这样的数据:

$ $ $ $ $ $ $ c $ 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 变量在 y 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)

我如何将这两个地块合并为一个?这个想法是将 y z 小节放在相邻的位置,它们都在同一个关联的 Specie 变量。用于 x 的条形将是例如蓝色,并且用于 y 的条形将是例如红色。

解决方案

  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( (Specie))
名称(df)= c(Specie,y,z,reshape2)

df = merge )

df = melt(df)

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


This is based on this post. Suppose that I have this data:

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

Notice that the Specie variable is the same across y and z.

I can create a bar plot for y and z, respectively, by the following:

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

How would I consolidate these two plots into one? The idea would be to have the y and z bars right beside each other, both within the same associated Specie variable. The bars for x would be, eg., blue and the bars for y would be, eg., red.

解决方案

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

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

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