gpt4 book ai didi

r - 平滑ggplot中的背对背条形图

转载 作者:行者123 更新时间:2023-12-04 09:47:59 26 4
gpt4 key购买 nike

我已经从回答question重新创建了这个情节。但是我想知道如何用平滑的图覆盖或替换条,即将X轴上的点链接在一起。如果他们正在替换条,那么最好用颜色填充它。我尝试过使用geom_smooth,但是我无法让它做我想做的事,将不胜感激。我正在讨论的问题的图解和代码如下。

set.seed(1)
df0 <- data.frame(Age = factor(rep(x = 1:10, times = 2)),
Gender = rep(x = c("Female", "Male"), each = 10),
Population = sample(x = 1:100, size = 20))

head(df0)
# Age Gender Population
# 1 1 Female 27
# 2 2 Female 37
# 3 3 Female 57
# 4 4 Female 89
# 5 5 Female 20
# 6 6 Female 86

library("ggplot2")
ggplot(data = df0, aes(x = Age, y = Population, fill = Gender)) +
geom_bar(data = subset(df0, Gender=="Female"),
stat = "identity") +
geom_bar(data = subset(df0, Gender=="Male"),
stat = "identity",
position = "identity",
mapping = aes(y = -Population)) +
scale_y_continuous(labels = abs) +
coord_flip()


Simple pyramid plot

最佳答案

不知道您遇到geom_smooth是什么问题,我只能猜测为什么它不起作用。也许与您将年龄作为数据框架中的一个因素这一事实有关?

我将Age转换为数字,以下代码对我有用:

df1 <- df0 %>% mutate(Age = as.numeric(as.character(Age)))
ggplot(df1,
aes(x = Age, y = Population, fill = Gender, colour = Gender)) +
geom_bar(data = subset(df1, Gender=="Female"), alpha = 0.5,
stat = "identity") +
geom_bar(data = subset(df1, Gender=="Male"), alpha = 0.5,
stat = "identity",
position = "identity",
mapping = aes(y = -Population)) +
geom_smooth(data = subset(df1, Gender=="Female"), se = F) +
geom_smooth(data = subset(df1, Gender=="Male"), se = F,
mapping = aes(y=-Population)) +
scale_y_continuous(labels = abs) +
coord_flip()


Resulting chart (smoothed lines overlaid on bars)

关于r - 平滑ggplot中的背对背条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244053/

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