我有一个看起来像这样的数据:
cats = c("cat1", "cat2", "cat3", "cat4")
df = data.frame(a = rnorm(100), b = as.factor(rep(cats, 25)))当我绘制它的时候,我得到的结果是这样的:ggplot(data = df) + geom_boxplot(aes(x = b, y = a, fill = b))

但是如果我想让它们在x轴上按cat4,cat3,cat2,cat1的顺序排列,我该怎么办呢?或者甚至是以完全不同的顺序?
发布于 2020-08-28 00:57:47
为ggplot定义变量as.factor()并不是强制性的。默认情况下,它将重新编码变量as.factor,但在本例中,它将遵循字母顺序。
但是,如果需要特定的顺序,则需要定义as.factor()并输入级别的顺序。
例如,如果您希望箱形图按其中值排序:
cats = c("cat1", "cat2", "cat3", "cat4")
df = tibble(a = rnorm(100), b = rep(cats, 25))
library(dplyr)
position <- df %>% group_by(b) %>% summarise(median=median(a)) %>%
arrange(desc(median)) %>% pull(b)
df$b <- factor(df$b,levels=position)
# order_wanted <- c(2,1,4,3)
# levels(df$b) <- paste0("cat",order_wanted)
library(ggplot2)
ggplot(data = df) + geom_boxplot(aes(x = b, y = a, fill = b))

https://stackoverflow.com/questions/63614946
复制相似问题