对具有两个级别ggplot2的堆叠条形图进行重新排序 [英] reorder stacked bar chart with two levels ggplot2
本文介绍了对具有两个级别ggplot2的堆叠条形图进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据:
# A tibble: 6 x 3
question category percent
<chr> <chr> <dbl>
1 No A 0.82
2 No C 0.8
3 No B 0.77
4 Yes B 0.23
5 Yes C 0.2
6 Yes A 0.18
然后我制作了堆积的条形图:
and I make a stacked bar chart:
data %>%
ggplot(aes(x = category, y = percent, fill = question)) +
geom_col(position = "fill") +
coord_flip()
但是我真正想要的是排列以是"下降的条形图.这意味着类别"B"被称为"B".应该在最前面,"C"表示中间的"和"A"表示在底部.
but what I really want is to arrange the bars descending in "Yes". That means Category "B" should be top, "C" in the middle", and "A" at the bottom.
如果我没有堆积图,则可以使用 reorder()
进行.但是我该如何使用堆积图呢?
If I didn't have a stacked chart I could do this with reorder()
. But how can I do this with a stacked chart?
数据:
structure(list(question = c("No", "No", "No", "Yes", "Yes", "Yes"
), category = c("A", "C", "B", "B", "C", "A"), percent = c(0.82,
0.8, 0.77, 0.23, 0.2, 0.18)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
推荐答案
排列
数据,设置因子并绘制图.
arrange
the data, set the factors and plot.
library(dplyr)
library(ggplot2)
data %>%
arrange(desc(question), percent) %>%
mutate(category = factor(category, unique(category))) %>%
ggplot(aes(x = category, y = percent, fill = question)) +
geom_col(position = "fill") +
coord_flip()
这篇关于对具有两个级别ggplot2的堆叠条形图进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文