在ggplot中平滑背靠背条形图

时间:2016-05-15 21:53:46

标签: r ggplot2

我已经从已回答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

1 个答案:

答案 0 :(得分:0)

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

我将年龄转换为数字&amp;以下对我有用:

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)