r - 重新排序每个方面的升序,以获得 ggplot 堆叠条形图
问题描述
library(tidyverse)
dat <- read.table(text = "A B C
1 23 234 324
2 34 534 12
3 56 324 124
4 34 234 124
5 123 534 654",
sep = "",
header = TRUE) %>%
gather(key = "variable", value = "value") %>%
group_by(variable) %>%
mutate(ind = as.factor(rep(1:5)),
perc = value / sum(value))
ggplot(dat, aes(variable, perc, fill = ind)) +
geom_col() +
scale_y_continuous(labels = scales::percent_format()) +
facet_grid(~ variable, scales = "free_x") +
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
上面的代码创建了您在上面也看到的堆叠条形刻面。每个ind
条形图部分的顺序与图例上显示的相同。
我更喜欢将每个ind
部分按升序(或降序)排列。多亏了@dgrtwo 和reorder_within函数,我通常可以做到这一点。
reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
new_x <- paste(x, within, sep = sep)
stats::reorder(new_x, by, FUN = fun)
}
但是 - 在我的例子中使用它会将上面的堆积条形图分解成下面的分解图。如何保留堆叠的条形图,并按ind
升序或降序排列?
注意 - 这可能不是其他几个“在方面内重新排序”问题的重复。我一直无法找到处理堆叠条形图的问题,以及我上面描述的问题。
ggplot(dat,
aes(reorder_within(ind, value, variable), perc, fill = ind)) +
geom_col() +
scale_y_continuous(labels = scales::percent_format()) +
facet_grid(~ variable, scales = "free_x") +
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
解决方案
经过一些操作后,这个答案变成了
dat <- dat %>% arrange(variable, -perc) %>% mutate(ordering = row_number())
aux <- with(dat, match(sort(unique(ind)), ind))
ggplot(dat, aes(x = variable, y = perc, fill = interaction(-ordering, variable))) +
geom_col() + facet_grid(~ variable, scales = "free_x") +
scale_fill_manual("ind", values = scales::hue_pal()(5)[dat$ind],
labels = with(dat, ind[aux]),
breaks = with(dat, interaction(-ordering, variable)[aux])) +
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
scale_y_continuous(labels = scales::percent_format())
与链接的答案相比,我主要对行进行了排序并添加了ordering
. 至于恢复默认调色板,我也使用hue_pal
了 from scales
. 由于使用scale_fill_manual
,这是需要的,在这种情况下,需要手动提供颜色。
推荐阅读
- php - 如何向 .htaccess 重定向规则添加例外
- grails - Grails 多项目:运行插件的自定义脚本
- java - Apache Ignite Cache - 从数据库中获取所有数据 -
- go - 接口列表的参数{}
- django - 将附加值关联到多字段
- javascript - 在 MongoDB 聚合中将 $sum 和 $avg 与 $addFields 一起使用
- bourbon - 对 Neat 2.0 网格媒体的困惑
- php - php 使用多个 num_rows 检查 2 条记录?
- python - 与 Flask 集成时,Ldap 模块失败
- origen-sdk - 可以将 Origen test_ids gem JSON 文件移动到 Git 存储库中的子目录吗?