更改ggplot2中

时间:2017-10-30 23:40:46

标签: r ggplot2

我想更改堆积条形图的顺序。 例如,在mpg我要订购c("4", "r", "f")

是改变因素水平的唯一方法吗?

library(ggplot2)
library(dplyr)
s <- ggplot(mpg, aes(fl, fill=drv)) + geom_bar(position="stack")
s

enter image description here

1 个答案:

答案 0 :(得分:5)

输入数据的结构是字符:

str(mpg$drv)

> chr [1:234] "f" "f" "f" "f" "f" "f" "f" "4" "4" "4" "4" "4" "4" "4" "4" "4" "4" "4" "r" "r" "r" "r" "r" "r" "r" "r" "r" "r" "4" "4" "4" "4" "f" "f" "f" "f" "f" "f" "f" "f" "f" "f" "f" ...

ggplot会自动将字符串转换为因子。您可以按如下方式查看默认顺序,此转换按字母顺序排列:

levels(as.factor(mpg$drv))
> "4" "f" "r"

要重新排序条形图而不更改原始数据,您只需在绘图本身内重构变量:

ggplot(mpg, aes(fl, fill = factor(drv, levels=c("4", "r", "f")))) + 
  geom_bar(position="stack") +
  labs(fill = "Drive")

比较结果:

enter image description here