在 ggplot2 中具有多个分组的有序条形图

时间:2021-02-16 18:52:20

标签: r ggplot2

我有这个未分组的数据(dput()在下面):

# A tibble: 12 x 3
   category1 category2 value
   <chr>     <chr>     <dbl>
 1 A         x         0.200
 2 A         y         0.32 
 3 A         z         0.46 
 4 B         x         0.52 
 5 B         y         0.420
 6 B         z         0.28 
 7 C         x         0.3  
 8 C         y         0.26 
 9 C         z         0.440
10 D         x         0.34 
11 D         y         0.440
12 D         z         0.58 

然后我绘制它:

data %>% 
  ggplot(aes(x = category2, y = value, fill = as.factor(category1))) + 
  geom_col(position = "dodge") + 
  coord_flip() 

enter image description here

现在我想对 category2 中的条进行排序,在 category1 中降序。

从此 previous post 我了解到您必须安排数据并创建/排序因子。但它并没有改变任何东西,我不知道为什么:

data %>% 
  arrange(desc(category1), value) %>%
  mutate(category2 = factor(category2, levels = unique(category2), ordered = TRUE)) %>%
  ggplot(aes(x = category2, y = value, fill = as.factor(category1))) + 
  geom_col(position = "dodge") + 
  coord_flip() 

我也尝试重新排序因子 per this post,但它没有做任何事情:

data %>% 
  mutate(category2 = factor(category2)) %>% 
  mutate(category2 = category2 %>% forcats::fct_reorder(value, sum)) %>% 
  ggplot(aes(x = category2, y = value, fill = as.factor(category1))) + 
  geom_col(position = "dodge") + 
  coord_flip()

enter image description here

编辑:忘记添加数据:

structure(list(category1 = c("A", "A", "A", "B", "B", "B", "C", 
"C", "C", "D", "D", "D"), category2 = c("x", "y", "z", "x", "y", 
"z", "x", "y", "z", "x", "y", "z"), value = c(0.2, 0.32, 0.46, 
0.52, 0.42, 0.28, 0.3, 0.26, 0.44, 0.34, 0.44, 0.58)), row.names = c(NA, 
-12L), class = c("tbl_df", "tbl", "data.frame"))

2 个答案:

答案 0 :(得分:2)

如果我猜对了,您可以像这样使用交互变量和 group 美学来实现您想要的结果:

  1. category2value 排列您的数据
  2. 添加一个新的类别变量作为 category2category1 的交互作用
  3. 通过 forecast::fct_inorder 设置新类别变量的顺序
  4. group 美学上映射新的类别变量
library(ggplot2)
library(dplyr)

data %>%
  arrange(category2, value) %>%
  mutate(
    category3 = interaction(category2, category1),
    category3 = forcats::fct_inorder(category3)
  ) %>%
  ggplot(aes(x = category2, y = value, fill = category1, group = category3)) +
  geom_col(position = "dodge") +
  coord_flip()

数据

data <- structure(list(category1 = c(
  "A", "A", "A", "B", "B", "B", "C",
  "C", "C", "D", "D", "D"
), category2 = c(
  "x", "y", "z", "x", "y",
  "z", "x", "y", "z", "x", "y", "z"
), value = c(
  0.2, 0.32, 0.46,
  0.52, 0.42, 0.28, 0.3, 0.26, 0.44, 0.34, 0.44, 0.58
)), class = "data.frame", row.names = c(
  "1",
  "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"
))

答案 1 :(得分:1)

tidytext::reorder_within 专为此用例构建。

library(tidytext)
data %>% 
  mutate(category1b = reorder_within(category1, value, within = category2)) %>%
  ggplot(aes(x = value, y = category2, group = category1b, fill = as.factor(category1))) + 
  geom_col(position = "dodge") 

enter image description here

相关问题