带有ggplot2的发散堆积条形图:图例中的因子排序问题

Posted

技术标签:

【中文标题】带有ggplot2的发散堆积条形图:图例中的因子排序问题【英文标题】:Divergent stacked bar chart with ggplot2: issue with factor ordering in legend 【发布时间】:2021-10-31 04:55:21 【问题描述】:

我正在尝试用ggplot2发散堆积条形图上绘制李克特量表数据。

我见过很多解决方案,其中我找到的最好的一个是this faceted solution(虽然不需要刻面)。我特别欣赏这样一个事实,即对于奇数刻度,中性值以 0 为中心。

我在这里以一种简化的方式复制了这个解决方案的想法(使用两个 geom_col() 和反向计数):

# Data sample
data <- 
    tibble(
        question = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"),
        option = c("Very bad", "Bad", "Neutral", "Good", "Exc",
                             "Very bad", "Bad", "Neutral", "Good", "Exc"),
        count = c(1, 10, 4, 5, 3, 3, 4, 5, 6, 8)
        ) %>% 
    mutate(
        option = option %>% factor(levels = c("Very bad", "Bad", "Neutral", "Good", "Exc")),
        count  = if_else(option == "Neutral", count/2, count)
        )

# Divergent stacked bar chart
data %>% 
    ggplot(aes(question, count, fill = option)) +
    geom_col(data = filter(data, option %in% c("Neutral", "Good", "Exc")),
                     position = position_stack(reverse = T)) +
    geom_col(data = filter(data, option %in% c("Neutral", "Bad", "Very bad")),
                     aes(y = -count)) +
    scale_fill_brewer(palette = "RdBu") +
    coord_flip()

结果如下:

如您所见,情节的顺序是正确的,但是图例和着色似乎忘记了因子排序(将ordered = T添加到因子没有帮助)。

如果我删除第二个geom_col(),那么一切都很好,但这显然不是我的目标。

如何强制ggplot2 保持图例中的因子排序?

【问题讨论】:

【参考方案1】:

问题是默认情况下未使用的因子水平会被丢弃。要解决您的问题,请在scale_fill_brewer 中设置drop=FALSE

不确定确切的内部结构,但这与您使用两个具有不同数据集的 geom_col 的事实有关。

library(ggplot2)

# Divergent stacked bar chart
ggplot(data, aes(question, count, fill = option)) +
  geom_col(data = filter(data, option %in% c("Neutral", "Good", "Exc")),
           position = position_stack(reverse = T)) +
  geom_col(data = filter(data, option %in% c("Neutral", "Bad", "Very bad")),
           aes(y = -count)) +
  scale_fill_brewer(palette = "RdBu", drop = FALSE) +
  coord_flip()

【讨论】:

太棒了!我尝试了很多选项(breakslabels 等),但没有找到 drop = FALSE 选项。非常感谢!

以上是关于带有ggplot2的发散堆积条形图:图例中的因子排序问题的主要内容,如果未能解决你的问题,请参考以下文章

Visual Studio 2016堆积条形图图例:更改标签标题

将 y 轴移动到中间并在每侧制作两个图例以用于 Plotly 发散条形图

Pandas 堆积条形图为大型图例重复颜色

Plotly:如何重命名 plotly express 堆积条形图的图例元素?

R 具有两个因子变量的堆积百分比条形图 - 如何在图中标记百分比,而不计算 NA?

Pandas - 绘制堆积条形图