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

2024-01-07

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

我见过很多解决方案,其中我发现最好的一个是这个多方面的解决方案 https://stackoverflow.com/questions/51201852/faceted-horizontal-divergent-stacked-bar-plot-including-negative-values-using-dp(虽然不需要方面)。我特别欣赏这样一个事实:对于奇数刻度,中性值以 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维持图例中的因子排序?


问题是默认情况下未使用的因子级别会被丢弃。解决您的问题集drop=FALSE in scale_fill_brewer:

不确定确切的内部结构,但这与您使用两个事实有关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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ggplot2 的发散堆积条形图:图例中的因子排序问题 的相关文章

随机推荐