2015-08-08 186 views
3

人口金字塔的情节我试图使用ggplot2dplyr(而不是plyr)后Simpler population pyramid in ggplot2与GGPLOT2和dplyr(而不是plyr)

重现简单的人口金字塔。

这里原来例如用plyr和种子

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

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

Pyramid plot with ggplot2 and plyr

工作正常。

但我怎么能生成dplyr,而不是此相同的情节?该示例在subset = .(g ==语句中使用plyr

我试图与dplyr::filter以下,但得到了一个错误:

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

Error in get(x, envir = this, inherits = inh)(this, ...) : 
    Mapping should be a list of unevaluated mappings created by aes or aes_string 

回答

4

您避免错误通过指定参数datageom_bar

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

你可以同时避免dplyrplyr时用最新版本ggplot2制作人口金字塔。

如果你有年龄性别群体的大小的计数,然后使用应答here

如果您的数据是在个人层面(如你的是),然后使用下列内容:

set.seed(321) 
test <- data.frame(v=sample(1:20,1000,replace=T), g=c('M','F')) 
head(test) 
# v g 
# 1 20 M 
# 2 19 F 
# 3 5 M 
# 4 6 F 
# 5 8 M 
# 6 7 F 

library("ggplot2") 
ggplot(data = test, aes(x = as.factor(v), fill = g)) + 
    geom_bar(data = subset(test, g == "F")) + 
    geom_bar(data = subset(test, g == "M"), 
      mapping = aes(y = - ..count..), 
      position = "identity") + 
    scale_y_continuous(labels = abs) + 
    coord_flip() 

enter image description here

+0

我得到类似的结果,除了y轴不排序....(它实际上是按字母顺序排序:1,10,11,12,13,14,15,16,17,18,19 ,2,20,21,...) – RockScience

+1

用'v'代替'as.factor(v)':现在它正在t order – RockScience

+0

@gjabel你能用这种方法将计数转换成百分比吗? – Prometheus