r - 反转堆叠条形图的顺序 - 在 ggplot 中突出显示
问题描述
# Create the data
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)) %>%
arrange(variable, -perc) %>%
mutate(ordering = row_number())
# Plot the data
ggplot(dat, aes(variable, perc, fill = interaction(
-ordering, variable)) # line #20
) +
geom_col(color = "white", size = 1.5, alpha = 0.25) +
facet_grid(~ variable, scales = "free_x") +
scale_fill_manual("ind", values = rep("black", length(dat$variable))) +
geom_col(data = dat %>% filter(ordering == 1),
color = "white",
size = 1.5,
fill = "red",
alpha = 0.5) +
theme_minimal() +
theme(panel.grid.major.x = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title.y = element_blank(),
legend.position = "none") +
scale_y_continuous(labels = scales::percent_format())
我在上面有突出显示的、多面的、堆叠的条形图。我想颠倒一切的顺序,所以我将-ordering
第 20 行更改为ordering
. 这给了我下面的图表。
您可以看到我的第 20 行更改确实颠倒了这个堆叠条形图的灰色部分的顺序。但是当我希望它们翻转到图的顶部时,红色的高光仍保留在图的底部。
我如何实现这一目标?我在许多类似的 SO 问题中尝试了分别添加position = position_fill(reverse = TRUE))
到 mygeom_col()
和 each 的答案,但这三个新尝试也没有奏效。我得到了与上面直接显示的相同的情节。
解决方案
这是一种类似但编码不同的方法,其中也包括alpha比例。我们的想法是保持不变,但为和dat
设置手动比例。直接使用;无需打电话。fill
alpha
ordering
interaction()
red <- 1L
n_ord <- length(unique(dat$ordering))
fill_scale <- c("red", rep("black", n_ord - 1L)) %>%
setNames(red * seq(n_ord))
alpha_scale <- c(0.5, rep(0.25, n_ord - 1L)) %>%
setNames(red * seq(n_ord))
# Plot the data
ggplot(dat, aes(variable, perc, fill = factor(red * ordering), alpha = factor(red * ordering))) +
# ggplot(dat, aes(variable, perc, fill = interaction(
# -ordering, variable)) # line #20
# ) +
geom_col(color = "white", size = 1.5) +
scale_fill_manual(guide = "none", values = fill_scale) +
scale_alpha_manual(guide = "none", values = alpha_scale) +
facet_grid(~ variable, scales = "free_x") +
theme_minimal() +
theme(panel.grid.major.x = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title.y = element_blank(),
legend.position = "none") +
scale_y_continuous(labels = scales::percent_format())
手动秤如下所示
fill_scale
1 2 3 4 5 "red" "black" "black" "black" "black"
alpha_scale
1 2 3 4 5 0.50 0.25 0.25 0.25 0.25
如果变量red
被切换,即 ,red <- -1L
我们可以重现 OP 的原始图:
推荐阅读
- mpi - Slurm MPI 错误:ORTE 守护程序失败
- python - 如何在 GPU 上处理字符串操作?
- progressive-web-apps - 新的更新可用消息和发布操作
- node.js - 超测附件:不支持的媒体类型:multipart/form-data;
- node.js - nginx 无法代理来自 node.js 应用程序的错误
- asp.net-core - 如何集成测试 SoapCore 端点?
- swiftui - 从 Observer 或外部 View 调用 ScrollView 的 scrollTo
- node.js - 电子辅助窗口不加载 HTML 文件
- flutter - 颤振的网络套接字
- python - 基于另一幅掩模图像测量掩模图像中多个点的宽度