ggplot并排geom_bar() [英] ggplot side by side geom_bar()
问题描述
我想用这个数据框的geom_bar()创建一个并排的barplot,
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
我试过使用这段代码,
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的长度相同。 %和percent1的长度与value相同,所以我很困惑。感谢您的帮助。
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.
首先通过 value
解析数据code> melt ,它会创建另一个名为 value $ c $的变量c>默认情况下,所以你需要重命名它(我称之为
百分比
)。然后,使用 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屋!