如何以整洁的方式重新排序因子水平? [英] How to reorder factor levels in a tidy way?

查看:15
本文介绍了如何以整洁的方式重新排序因子水平?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我通常使用如下代码对 ggplot 中的条形进行重新排序或其他类型的地块.

Hi I usually use some code like the following to reorder bars in ggplot or other types of plots.

正态图(无序)

library(tidyverse)
iris.tr <-iris %>% group_by(Species) %>% mutate(mSW = mean(Sepal.Width)) %>%
  select(mSW,Species) %>% 
  distinct()
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) +
  geom_point(stat = "identity")

对因子排序 + 有序图

iris.tr$Species <- factor(iris.tr$Species,
                          levels = iris.tr[order(iris.tr$mSW),]$Species,
                          ordered = TRUE)
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) + 
  geom_point(stat = "identity")

因子行对我来说非常不舒服,我想知道为什么 arrange() 或其他一些函数不能简化它.我错过了什么?

The factor line is extremely unpleasant to me and I wonder why arrange() or some other function can't simplify this. I am missing something?

注意:

这不起作用,但我想知道 tidyverse 中是否存在这样的东西.

This do not work but I would like to know if something like this exists in the tidyverse.

iris.tr <-iris %>% group_by(Species) %>% mutate(mSW = mean(Sepal.Width)) %>%
  select(mSW,Species) %>% 
  distinct() %>% 
  arrange(mSW)
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) + 
  geom_point(stat = "identity")

推荐答案

使用‹forcats›:

iris.tr %>%
    mutate(Species = fct_reorder(Species, mSW)) %>%
    ggplot() +
    aes(Species, mSW, color = Species) +
    geom_point()

这篇关于如何以整洁的方式重新排序因子水平?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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