更改ggplot2中堆积填充列的顺序 [英] Change the order of stacked fill columns in ggplot2

查看:289
本文介绍了更改ggplot2中堆积填充列的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to change the order of a stacked bar chart. For example, in mpg I want to order the to c("4", "r", "f")

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

Is the only approach to change the level of the factors?

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

推荐答案

输入数据的结构为字符:

The structure of the input data is character:

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将自动将字符串转换为因子.您可以看到默认顺序如下,该转换将按字母顺序对它们进行排名:

ggplot will automatically convert character strings to a factor. You can see the default ordering as follows, and this conversion ranks them alphabetically:

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

要在不更改原始数据的情况下对条形图进行重新排序,只需在图自身中重构变量即可:

To reorder the barplot without changing the original data, you can just refactor the variable within plot itself:

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

比较结果:

这篇关于更改ggplot2中堆积填充列的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆