gpt4 book ai didi

r - ggplot 并排 geom_bar()

转载 作者:行者123 更新时间:2023-12-01 08:12:37 35 4
gpt4 key购买 nike

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

> 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 轴上的值和百分比作为并排条形图。我曾尝试使用此代码,
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 的长度与值相同,所以我很困惑。谢谢您的帮助。

最佳答案

您将需要 melt您的数据先过 value .它将创建另一个名为 value 的变量默认情况下,因此您需要重命名它(我称之为 percent )。然后,使用 fill 绘制新数据集为了将数据分组,和position = "dodge"为了将酒吧并排(而不是彼此重叠)

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

enter image description here

关于r - ggplot 并排 geom_bar(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070547/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com