首页 > 解决方案 > ggplot2中具有多个分组的有序条形图

问题描述

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

# 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() 

在此处输入图像描述

现在我想订购category2中的条形,按category1递减。

上一篇文章中,我了解到您必须安排数据并创建/排序因子。但它并没有改变任何东西,我不知道为什么:

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

我也尝试根据这篇文章重新排序因子,但它没有做任何事情:

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

在此处输入图像描述

编辑:忘记添加数据:

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

标签: rggplot2

解决方案


如果我说得对,您可以通过使用交互变量和group美学来实现您想要的结果,如下所示:

  1. category2按和排列您的数据value
  2. 添加一个新的类别变量作为和的category2交互category1
  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"
))

推荐阅读