ggplot2 中更简单的人口金字塔 [英] Simpler population pyramid in ggplot2

查看:35
本文介绍了ggplot2 中更简单的人口金字塔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 ggplot2 创建一个人口金字塔.这个问题在之前被问到,但我相信解决方案一定要简单得多.

I want to create a population pyramid with ggplot2. This question was asked before, but I believe the solution must be far simpler.

test <- (data.frame(v=rnorm(1000), g=c('M','F')))
require(ggplot2)
ggplot(data=test, aes(x=v)) + 
    geom_histogram() + 
    coord_flip() + 
    facet_grid(. ~ g)

生成此图像.在我看来,创建人口金字塔这里缺少的唯一步骤是反转第一个方面的 x 轴,使之从 50 变为 0,同时保持第二个方面不变.有人可以帮忙吗?

Produces this image. In my opinion, the only step missing here to create a population pyramid is to invert the x axis of the first facet, so that is goes from 50 to 0, while keeping the second untouched. Can anyone help?

推荐答案

这是一个没有分面的解决方案.首先,创建数据框.我使用了 1 到 20 之间的值来确保没有一个值为负(使用人口金字塔,您不会得到负计数/年龄).

Here is a solution without the faceting. First, create data frame. I used values from 1 to 20 to ensure that none of values is negative (with population pyramids you don't get negative counts/ages).

test <- data.frame(v=sample(1:20,1000,replace=T), g=c('M','F'))

然后为每个 g 值分别组合两个 geom_bar() 调用.对于 F 计数按原样计算,但对于 M 计数乘以 -1 以获得相反方向的柱线.然后 scale_y_continuous() 用于获取轴的漂亮值.

Then combined two geom_bar() calls separately for each of g values. For F counts are calculated as they are but for M counts are multiplied by -1 to get bar in opposite direction. Then scale_y_continuous() is used to get pretty values for axis.

require(ggplot2)
require(plyr)    
ggplot(data=test,aes(x=as.factor(v),fill=g)) + 
  geom_bar(subset=.(g=="F")) + 
  geom_bar(subset=.(g=="M"),aes(y=..count..*(-1))) + 
  scale_y_continuous(breaks=seq(-40,40,10),labels=abs(seq(-40,40,10))) + 
  coord_flip()

更新

作为参数 subset=. 在最新的 ggplot2 版本中被弃用,使用 subset() 函数可以获得相同的结果.>

UPDATE

As argument subset=. is deprecated in the latest ggplot2 versions the same result can be atchieved with function subset().

ggplot(data=test,aes(x=as.factor(v),fill=g)) + 
  geom_bar(data=subset(test,g=="F")) + 
  geom_bar(data=subset(test,g=="M"),aes(y=..count..*(-1))) + 
  scale_y_continuous(breaks=seq(-40,40,10),labels=abs(seq(-40,40,10))) + 
  coord_flip()

这篇关于ggplot2 中更简单的人口金字塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆