【问题标题】:Easily reorder factor levels after tidying or melting整理或融化后轻松重新排序因子水平
【发布时间】: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')

【问题讨论】:

    标签: r ggplot2 tidyr


    【解决方案1】:

    数据

    df$education <- factor(df$education, c("Elementary", "High School", 
                            "College"))
    ddf <- df %>% 
           gather(variable, value, -gender) %>%
           group_by(value, variable, gender)  %>%
           summarise(freq = n())
    

    代码

    lvl <- unlist(lapply(df[, -2], function(.) levels(as.factor(.))))
    ddf$value <- factor(ddf$value, lvl)
    ddf %>% ggplot(aes(x = value, y = freq, group = gender)) + 
            geom_bar(aes(fill = gender), stat = 'identity', 
                     position = 'dodge') + 
            facet_wrap(~variable, scales='free_x')
    

    说明

    gathereducationincomeage 中的值转换为字符向量。 ggplot 然后使用这些值的规范顺序(即字母顺序)。如果您希望它们具有特定的顺序,您应该首先将列转换为一个因子,然后按照您喜欢的顺序分配级别(正如您所提到的)。我只是对原始级别进行了排序(并默默地将数字 income 转换为一个因素 - 可能需要对您的代码进行一些调整)。但它表明,假设级别在原始数据集中的顺序正确,您不必自己对任何级别进行硬编码。

    所以在你的真实情况下,你应该做的是:

    1. 将字符向量value转换为因子
    2. 按照您希望它们在ggplot 中显示的顺序分配级别

    情节

    【讨论】:

    • 这真的很漂亮。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2022-01-10
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多