[英]Change order of segments in stacked barplot
How can I change the order of the segments in the following stacked barplot from --
(left) to ++
(right) and NA
on the right?如何将以下堆叠条形图中的段顺序从
--
(左)更改为++
(右)和右侧的NA
?
library(dplyr)
library(ggplot2)
library(tidyr)
size <- 100
df <- data.frame(item1 = sample(c(1:5, 1:5, 99), size = size, replace = TRUE),
item2 = sample(c(1:5, 1:4, 99), size = size, replace = TRUE),
item3 = sample(c(1:5, 1:3, 99), size = size, replace = TRUE),
item4 = sample(c(1:5, 1:5, 99), size = size, replace = TRUE),
item5 = sample(c(1:5, 1:4, 99), size = size, replace = TRUE))
# Stacked barplot
df %>% pivot_longer(cols = starts_with("item")) %>%
group_by(name) %>%
count(value) %>%
mutate(perc = 100 / sum(n) * n) %>%
ungroup() %>%
mutate(value = factor(value, levels = c(1:5, 99), labels = c("--", "-", "0", "+", "++", "NA"))) %>%
ggplot(aes(x = name, y = perc, fill = value)) + geom_col() +
coord_flip()
Created on 2022-12-12 with reprex v2.0.2创建于 2022-12-12,使用reprex v2.0.2
You can reverse the order of the stack by using position_stack(reverse = TRUE)
:您可以使用
position_stack(reverse = TRUE)
堆栈的顺序:
set.seed(123)
library(tidyr)
library(ggplot2)
library(dplyr)
df %>% pivot_longer(cols = starts_with("item")) %>%
group_by(name) %>%
count(value) %>%
mutate(perc = 100 / sum(n) * n) %>%
ungroup() %>%
mutate(value = factor(value, levels = c(1:5, 99), labels = c("--", "-", "0", "+", "++", "NA"))) %>%
ggplot(aes(x = name, y = perc, fill = value)) +
geom_col(position = position_stack(reverse = TRUE)) +
coord_flip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.