与ggplot2和dplyr(而不是plyr)的人口金字塔图 [英] Population pyramid plot with ggplot2 and dplyr (instead of plyr)

查看:788
本文介绍了与ggplot2和dplyr(而不是plyr)的人口金字塔图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从后期重现简单的人口金字塔>



工作正常。



但是,如何使用 dplyr 生成相同的情节?该示例使用 subset =。(g == 语句中的 plyr



我尝试了以下的 dplyr :: filter ,但出现错误:

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

get(x,envir = this,inherits = inh)(this,...):
映射应该是由aes或aes_string
创建的未评估映射的列表
pre>

解决方案

您可以通过指定参数数据 code> geom_bar :

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


I am trying to reproduce the simple population pyramid from the post Simpler population pyramid in ggplot2

using ggplot2 and dplyr (instead of plyr).

Here is the original example with plyr and a seed

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

Works fine.

But how can I generate this same plot with dplyr instead? The example uses plyr in the subset = .(g == statements.

I have tried the following with dplyr::filter but got an error:

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

解决方案

You avoid the error by specifying the argument data in geom_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() 

这篇关于与ggplot2和dplyr(而不是plyr)的人口金字塔图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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