R中的人口金字塔图

我是R的新手,正在尝试创建一个类似于这里https://klein.uk/teaching/viz/datavis-pyramids/的人口金字塔图。我有一个包含两个变量性别和年龄组的数据集,如下所示:

   sex       age_group

1   Male      20-30
2   Female    50-60
3   Male      70-80
4   Male      10-20
5   Female    80-90
...   ...       ...

这是我使用的代码

ggplot(data = pyramid_graph(x = age_group,fill = sex)) +
geom_bar(data = subset(pyramid_graph,sex == "F")) + 
geom_bar(data = subset(pyramid_graph,sex == "M")) + 
mapping = aes(y = - ..count.. ),position = "identity") + 
scale_y_continuous(labels = abs) +
coord_flip()

我没有从R中得到任何错误,但是当我执行此代码时,会生成空白图像。

有人可以帮忙吗? 谢谢

iCMS 回答:R中的人口金字塔图

使用来自您在问题中引用的同一网站的类似输入数据集:

# Obtain source data
load(url("http://klein.uk/R/Viz/popGH.RData"))
# Convert to summary table
df <- as_tibble(popGH) %>% 
        mutate(AgeDecade=as.factor(floor(AGE/10)*10)) %>% 
        group_by(SEX,AgeDecade) %>% 
        dplyr::summarise(N=n(),.groups="drop") %>% 
        # A more transparent way of managing the transformation to get "Females to the left".
        mutate(PlotN=ifelse(SEX=="Female",-N,N)) 
# Create the plot
df %>% ggplot() +
   geom_col(aes(fill=SEX,x=AgeDecade,y=PlotN)) +
   scale_y_continuous(breaks=c(-2*10**5,2*10**5),labels=c("200k","0","200k")) +
   labs(y="Population",x="Age group") +
   scale_fill_discrete(name="Sex") +
   coord_flip()

给予

enter image description here

请注意,我创建了一个新列以在图中创建“左侧女性”效果。通常,我会避免这样做,而将依靠各种ggplot函数的选项来实现同一件事(就像您尝试做的那样)。但是,在这种情况下,我认为使用多余的列而不是对mapping进行kodify更加透明(且简单)。

本文链接:https://www.f2er.com/2001908.html

大家都在问