【发布时间】:2015-10-13 18:46:03
【问题描述】:
我正在尝试有效地绘制一系列双变量条形图。每个图应显示按性别分布的一系列人口统计变量的案例频率。这段代码运行良好但是在创建整理变量variable 时,它的级别是不同人口统计变量的所有级别。由于它是一个新因子,R 以它自己的字母顺序排列因子水平。但是,正如您从下面的“变量”的因子水平和结果图中可以看到的那样,它们的顺序没有意义。即收入类别和教育水平一样乱序。
在我的真实数据集中,因子水平要多得多,因此对variable 进行简单的重新调整是可能的,但实际上并不可行。我想到的一种选择是不要将melt 变量转换为variable,而是尝试做一些版本的summarise_each()。但我无法让它发挥作用。
感谢您的帮助。
#Age variable
age<-sample(c('18 to 24', '25 to 45', '45+'), size=100, replace=T)
#gender variable
gender<-sample(c('M', 'F'), size=100, replace=T)
#income variable
income<-sample(c(10,20,30,40,50,60,70,80,100,110), size=100, replace=T)
#education variable
education<-sample(c('High School', 'College', 'Elementary'), size=100, replace=T)
#tie together in df
df<-data.frame(age, gender, income, education)
#begin tidying
df %>%
#tidy, not gender
gather(variable, value, -c(gender))%>%
#group by value, variable, then gender
group_by(value, variable, gender) %>%
#summarise to obtain table cell frequencies
summarise(freq=n())%>%
#begin plotting, value (categories) as x-axis, frequency as y, gender as grouping variable, original variable as the facetting
ggplot(aes(x=value, y=freq, group=gender))+geom_bar(aes(fill=gender), stat='identity', position='dodge')+facet_wrap(~variable, scales='free_x')
【问题讨论】: