ggplot 并排 geom_bar() [英] ggplot side by side geom_bar()

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

问题描述

我想使用这个数据框的 geom_bar() 创建一个并排的条形图,

I want to create a side by side barplot using geom_bar() of this data frame,

> dfp1
   value   percent1   percent
1 (18,29] 0.20909091 0.4545455
2 (29,40] 0.23478261 0.5431034
3 (40,51] 0.15492958 0.3661972
4 (51,62] 0.10119048 0.1726190
5 (62,95] 0.05660377 0.1194969

x 轴上的值和百分比作为并排条形图.我曾尝试使用此代码,

With values on the x-axis and the percents as the side by side barplots. I have tried using this code,

p = ggplot(dfp1, aes(x = value, y= c(percent, percent1)), xlab="Age Group")
p = p + geom_bar(stat="identity", width=.5)  

但是,我收到此错误:错误:美学的长度必须为 1,或与 dataProblems:value 的长度相同.我的百分比和百分比 1 的长度与值相同,所以我很困惑.谢谢您的帮助.

However, I get this error: Error: Aesthetics must either be length one, or the same length as the dataProblems:value. My percent and percent1 are the same length as value, so I am confused. Thanks for the help.

推荐答案

你需要先melt你的数据而不是 value.默认情况下,它会创建另一个名为 value 的变量,因此您需要重命名它(我称之为 percent).然后,使用 fill 绘制新数据集以将数据分组,并使用 position = "dodge" 将条并排放置(而不是放在互相顶)

You will need to melt your data first over value. It will create another variable called value by default, so you will need to renames it (I called it percent). Then, plot the new data set using fill in order to separate the data into groups, and position = "dodge" in order put the bars side by side (instead of on top of each other)

library(reshape2)
library(ggplot2)
dfp1 <- melt(dfp1)
names(dfp1)[3] <- "percent"
ggplot(dfp1, aes(x = value, y= percent, fill = variable), xlab="Age Group") +
   geom_bar(stat="identity", width=.5, position = "dodge")  

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

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