对分组变量中的因子进行重新排序,以便可以使用ggplot2对其进行绘制

博士 菲什波利斯

我正在尝试制作一张图表,显示按性别种族划分的平均年龄。图表本身应以最低平均年龄到最高平均年龄的顺序显示此信息,并按总体性别分组。

我正在根据按工作类别,性别/种族,性别和平均年龄分组的数据集进行工作。我已经可以使用以下代码按性别成功订购此商品:

rsltProf = rslt %>% 
      filter(group == "Professionals" & avg > 0) %>%
      group_by(gender) %>%
      arrange(avg, .by_group = TRUE)
str(rsltProf$genXrce)

我得到以下输出:

    group          genXrce   gender      avg
1 Professionals Female-Asian Female 33.25397
2 Professionals Female-Other Female 37.55000
3 Professionals Female-White Female 39.89632
4 Professionals Female-Black Female 39.94118
5 Professionals   Male-Other   Male 32.80000
6 Professionals   Male-Asian   Male 37.86667
7 Professionals   Male-Black   Male 38.69767
8 Professionals   Male-White   Male 38.85294
Factor w/ 9 levels "Female-Asian",..: 4 2 3 1 9 7 8 6

太好了,这正是我想要的。但是,当我用ggplot对其进行图形处理时,它会产生以下结果:

输出

clearly, this is because ggplot2 is graphing by the order of the factors rather than the order of the arranged dataframe. I have tried multiple ways to relevel the genXrce based on how it's arranged in the above code to no avail, including relevel, mutate, and reorder.

My question is: How can I reorder/arrange the data in such a way that ggplot2 will produce a graph that gives ascending averages grouped by gender, in the same way as the table I produced does? Any advice much appreciated.

EDIT 1: In a below comment it was suggested to do use forcats or a similar function to arrange the graph through ggplot. An example like so:

ggplot(data = rsltProf, mapping = aes(x =fct_reorder(!!as.name(genXrce), avg), y =  avg, fill = genXrce))

但是,这将平均排列所有genXrce因子,并且不再按性别分开。要明确的是,小节的顺序应与表格相同->女白,女黑,女其他,女亚洲,男白,男黑....

上面的ggplot产生了下面的图表,该图表混杂了性别: 第二张图

尼尔夫

给定数据框rsltProf以所需顺序排列的行,将其转换genXrce为该列的行顺序指定的级别的因子:

library(dplyr)
library(ggplot2)

rsltProf %>% 
  mutate(genXrce = factor(genXrce, levels = unique(.$genXrce))) %>% 
  ggplot(aes(genXrce, avg)) + geom_col()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 tidyverse 中的 forcats 和 ggplot2 包进行绘图的重新排序因子

使用 ggplot2 根据两个因子变量(在 x 轴中)对箱线图进行排序

使用ggplot2对框线图进行分组和重新排序

R / ggplot2中是否有一种方法可以对图例进行重新排序以匹配其行位置?

在熊猫中对分组数据进行排序

将for循环的输出添加到data.frame中,以便我可以在R中使用ggplot2对其进行图形处理

R-使用ggplot2在函数中对条形图进行重新排序

将@State变量传递给Class,以便可以对其进行更改

如何使用qqplot2对因子进行箱线图绘制并根据连续变量对因子之一进行排序

在Laravel中对分页变量进行排序

使用 ggplot2 对条进行分组

如何通过引用传递,以便可以在调用函数中对其进行修改?

在没有会话变量的MySQL中对分组数据进行排序?

对字符串进行排序,以便可以与LINQ一起使用

如何在mysql中按值对分组进行排序

使用XSLT 1.0对分组的项目进行排序

我可以在 ggplot2 中对图例中的项目进行分组吗?

使用R对分组变量进行非线性优化

如何对CSS样式的每个逗号分隔值进行分类,以便可以对其进行累加?

按Lodash对分组对象进行排序

根据两列的总和之比对因子进行重新排序-按要重新排序的因子分组

R:对ggplot中的变量名称进行重新排序

是否可以使用 Class CoordCartesian 对象在 ggplot2 中绘制矩形

如何使用Spring MVC返回视频,以便可以使用html5 <video>标签进行导航?

如何将mapply转换为pmap或类似的数据,以便可以在R中对数据进行分组

如何读取YAML文件中的组件,以便可以使用ruamel.yaml编辑其键值?

Python:如何从OpenStreetMaps中将水路作为图形导入,以便可以使用networkx进行图形分析

使用ggplot2绘制拟合的glm输出以进行交互

使用ggplot2进行多面板绘制?