r - 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"))
解决方案
如果我说得对,您可以通过使用交互变量和group
美学来实现您想要的结果,如下所示:
category2
按和排列您的数据value
- 添加一个新的类别变量作为和的
category2
交互category1
- 通过设置新类别变量的顺序
forecast::fct_inorder
- 将新类别变量映射到
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"
))
推荐阅读
- mysql - 在 mySQL 中将随机数分配给具有 NULL 值的列
- javascript - 如何在条件字符串中使用多个 async / await 调用?
- reactjs - 静态 S3 网站 (React SPA) 记录到 Elasticsearch
- r - 我如何显示最匹配的汽车名称和余弦相似度值并将它们显示在两个单独的列上?(需要提取第二大的值)
- neo4j - 我无法通过 neo4j 创建数据
- c# - 如何使用 C# 从 myjson.com 动态更新 json 文件?
- firebase - 拥有隔离用户组的最可靠方法是什么?
- java - 在 Apache POI(docx)中包装文本?
- java - 在 Tomcat 服务器中部署 war 文件的问题
- android - 混淆 Android 库 AAR