首页 > 解决方案 > 反转堆叠条形图的顺序 - 在 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 的答案,但这三个新尝试也没有奏效。我得到了与上面直接显示的相同的情节。

标签: rggplot2

解决方案


这是一种类似但编码不同的方法,其中也包括alpha比例。我们的想法是保持不变,但为和dat设置手动比例。直接使用;无需打电话。fillalphaorderinginteraction()

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 的原始图:

在此处输入图像描述


推荐阅读