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

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

问题描述

我想用ggplot2创建一个人口金字塔。这个问题被问及 之前,但我相信解决方案必须简单得多。 (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,同时保持第二方面不变。任何人都可以帮忙吗?



解决方案

这是一个没有分面的解决方案。首先,创建数据框。我使用了从1到20的值,以确保没有任何值是负值(人口金字塔不会得到负值/年龄)。

 <$ (v = sample(1:20,1000,replace = T),g = c('M','F'))

然后为每个 g分别组合两个 geom_bar()调用值。对于> F计数按原样计算,但是对于 M 计数乘以-1得到反方向的小节。然后使用 scale_y_continuous()来获得轴的漂亮值。

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



UPDATE



在最新的 ggplot2 版本中不推荐使用参数 subset =。,同样的结果可以通过函数 subset()

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


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)

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?

解决方案

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

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

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天全站免登陆