R 按ggplot中的因子对x值重新排序
假设我有以下生成绘图的命令R 按ggplot中的因子对x值重新排序,r,ggplot2,R,Ggplot2,假设我有以下生成绘图的命令 mpg %>% filter(manufacturer == "toyota") %>% ggplot( aes(x=model, y=hwy, fill=class)) + theme(axis.text.x = element_text(angle = 20, hjust = 1)) + geom_boxplot() 是否有一种方法可以按因子对x标签进行排序,以便具有相同类的所有箱线图彼此相邻 谢谢大家! 我们可以
mpg %>% filter(manufacturer == "toyota") %>%
ggplot( aes(x=model, y=hwy, fill=class)) +
theme(axis.text.x = element_text(angle = 20, hjust = 1)) +
geom_boxplot()
是否有一种方法可以按因子对x标签进行排序,以便具有相同类的所有箱线图彼此相邻
谢谢大家! 我们可以使用
因子
重新排序<代码>按“类别”、“模型”排列数据,然后将“模型”转换为因子,并将级别指定为唯一的值,然后重新运行ggplot
library(dplyr)
library(ggplot2)
mpg %>%
filter(manufacturer == "toyota") %>%
arrange(class, model) %>%
mutate(model = factor(model, levels = unique(model))) %>%
ggplot( aes(x=model, y=hwy, fill=class)) +
theme(axis.text.x = element_text(angle = 20, hjust = 1)) +
geom_boxplot()
-输出
另一个选项是fct\u重新排序
library(forcats)
mpg %>%
filter(manufacturer == "toyota") %>%
ggplot( aes(x=fct_reorder(model, class), y=hwy, fill=class)) +
theme(axis.text.x = element_text(angle = 20, hjust = 1)) +
geom_boxplot()