hed*_*ds1 3 r ggplot2 tidyverse
我的数据(复制如下)包含三个变量:(Tools分类变量)、Proficiency(值列)和Category(分组列)。我想根据Proficiency值的降序对列进行排序,同时保持Category组的分离,并且不使用facet_gridor facet_wrap(因为我正在使用coord_flip)。可重现的数据如下。为了排序,我根据因子指定Category的级别。ToolsCategory
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)))
Run Code Online (Sandbox Code Playgroud)
这会产生下面的图,它显然没有按Proficiency值的降序分组。
完成所需分组和排序的一种方法是在调用中使用并重新facet_grid()排序:ToolsProficiencyaes
ggplot(data = df1, aes(x = reorder(Tools, -Proficiency), y = Proficiency, fill = Category)) +
geom_col() +
facet_grid(~ Category, scales = "free_x", space = "free_x")
Run Code Online (Sandbox Code Playgroud)
但是,我想用于coord_flip这个情节。不幸的是,coord_flip似乎不能很好地配合facet_grid(github问题一、二)。
可以预见的是,排序Proficiency而不使用 usingfacet_grid会导致绘图覆盖Category组。
我想要的输出是上面的图像,其中Tools首先按 排序Category,其次按 排序Proficiency。任何帮助深表感谢。
这个答案看起来很有希望,但在这里应用类似的方法对我来说不起作用;下面的操作只是设置了通过以下方式订购的图Proficiency:
df1$Tools <- with(df1, factor(Tools, levels=Tools[order(ave(Proficiency, Category, FUN=min),Proficiency)]))`
Run Code Online (Sandbox Code Playgroud)
一种方法是将数据框排列成所需的顺序,并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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1651 次 |
| 最近记录: |