带ggplot2的发散堆叠条形图:图例中的系数排序问题 [英] Divergent stacked bar chart with ggplot2: issue with factor ordering in legend
本文介绍了带ggplot2的发散堆叠条形图:图例中的系数排序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用ggplot2
在分散堆叠条形图上绘制Likert刻度数据。
我看到了很多解决方案,其中我找到的最好的解决方案是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
保持图例中的因子顺序?
推荐答案
问题是默认情况下会删除未使用的因子级别。要解决您的问题,请在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()
这篇关于带ggplot2的发散堆叠条形图:图例中的系数排序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文