如何整齐地对因子水平进行重新排序? [英] How to reorder factor levels in a tidy way?

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

问题描述

我通常使用类似以下的代码对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")

因素行对我来说非常不愉快,我想知道为什么 ranging()或其他一些函数无法简化此过程。我想念什么吗?

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


推荐答案

使用‹< a href = http://forcats.tidyverse.org/ rel = noreferrer> forcats ›:

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

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

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