【问题标题】:Reorder columns by value while maintaining group order按值重新排序列,同时保持组顺序
【发布时间】:2019-07-03 01:09:41
【问题描述】:

我的数据(转载如下)包含三个变量,Tools(分类变量)、Proficiency(值列)和Category(分组列)。 我想根据Proficiency 值的降序对列进行排序,同时保持Category 组的分离,并且不使用facet_gridfacet_wrap(因为我使用的是coord_flip)。可重复的数据如下。为了按Category 排序,我根据Category 因子指定Tools 的级别。

library(tidyverse)

df1 <- structure(list(Tools = structure(c(1L, 8L, 9L, 5L, 6L, 10L, 2L, 
3L, 4L, 7L), .Label = c("Tool1", "Tool7", "Tool8", "Tool9", "Tool4", 
"Tool5", "Tool10", "Tool2", "Tool3", "Tool6"), class = "factor"), 
    Proficiency = c(3, 2, 5, 4, 3, 3, 3, 2, 2, 2), Category = structure(c(1L, 
    3L, 3L, 2L, 2L, 3L, 1L, 1L, 1L, 2L), .Label = c("Category1", 
    "Category2", "Category3"), class = "factor")), row.names = c(NA, 
-10L), class = "data.frame")

df1$Tools <- factor(df1$Tools, levels = df1$Tools[order(df1$Category)])

ggplot(data = df1, aes(x = Tools, y = Proficiency, fill = Category)) +
  geom_col() + 
  scale_x_discrete(limits = rev(levels(df1$Tools)))

这产生了下面的图,它显然没有按Proficiency 值的降序分组。

实现所需分组和排序的一种方法是使用 facet_grid() 并在 aes 调用中基于 Proficiency 重新排序 Tools

ggplot(data = df1, aes(x = reorder(Tools, -Proficiency), y = Proficiency, fill = Category)) + 
  geom_col() + 
  facet_grid(~ Category, scales = "free_x", space = "free_x")

但是,我想在这个情节中使用coord_flip。不幸的是,coord_flip 似乎不适用于facet_grid(github 问题onetwo) .

可以预见的是,在不使用facet_grid 的情况下按Proficiency 排序会导致绘图覆盖Category 组。

我想要的输出是上面的图像,其中Tools首先按Category排序,其次按Proficiency排序。非常感谢任何帮助。

This answer 看起来很有希望,但在这里应用类似的方法对我不起作用;下面的操作只是设置了通过Proficiency 订购的情节:

df1$Tools <- with(df1, factor(Tools, levels=Tools[order(ave(Proficiency, Category, FUN=min),Proficiency)]))`

【问题讨论】:

标签: r ggplot2 tidyverse


【解决方案1】:

一种方法是将您的数据框排列成所需的顺序,并按照该顺序设置Tools 的因子水平。

library(dplyr)
library(ggplot2)

df1 %>%
  arrange(desc(Category), desc(Proficiency)) %>%
  mutate(Tools = factor(Tools, levels = Tools)) %>%
  ggplot(aes(x = Tools, y = Proficiency, fill = Category)) + 
  geom_col() + 
  coord_flip() 

【讨论】:

    【解决方案2】:

    使用函数fct_infreq( )

    
    ggplot(df2, aes(fct_infreq(x),y))+
     geom_col()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2015-03-09
      相关资源
      最近更新 更多