r - 使用 ggplot2 的发散堆积条形图 : issue with factor ordering in legend

标签 r ggplot2 legend r-factor

我正在尝试使用 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()

这给出了以下结果:

Ggplot divergent stacked bar chart

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

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

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

最佳答案

问题是默认情况下未使用的因子级别会被丢弃。要解决您的问题,请在 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()

关于r - 使用 ggplot2 的发散堆积条形图 : issue with factor ordering in legend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69017983/

相关文章:

R:向 ggplot 添加自定义图例

Gnuplot:系列标题之间的垂直间距

r - 如何查找监控位置的开始和结束日期

r - pryr::mem_used() 在内存单位(MB、GB、...)之间的转换

在不超过我的 RAM 的情况下分块读取 20GB 文件 - R

r - 如何计算在收到阳性结果之前阴性观察的数量

r - 点数据集到格网数据集的平均值

r - 绘制图例向左移动ggplot

r - R中的更多靶心绘图

r - 中间有 y 轴的多面 ggplot