ggplot2||分面图facet_grid()/facet_wrap()自定义标签顺序

需要做分面图,但是出来的效果顺序不太对!
比如说正常的标签顺序是A1, A2, A3, ..., A11, ...
但是出来的效果却是A1, A11, ..., A2, A21, ..., A3, ...
因此:

起因

  • 数据来源
  • 作图
rm(list = ls(all=TRUE))
library(reshape2)
library(ggplot2)
head(tips)
> head(tips)
  total_bill  tip    sex smoker day   time size
1      16.99 1.01 Female     No Sun Dinner    2
2      10.34 1.66   Male     No Sun Dinner    3
3      21.01 3.50   Male     No Sun Dinner    3
4      23.68 3.31   Male     No Sun Dinner    2
5      24.59 3.61 Female     No Sun Dinner    4
6      25.29 4.71   Male     No Sun Dinner    4
p <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
p1 <- p + facet_grid(sex ~day )
p1
  • 效果


    facet

需求

  • [1]

经过&结果

查阅相关资料介绍需要数据组group序列因子化并设置levels,即factor(group, levels=c("1","2")),可参考这个网址!具体操作如下:

#group <- factor(group,levels = c("1","2"))
tips <- within(tips, day <- factor(day, levels = c("Sat", "Thur", "Fri", "Sun")))
with(tips, levels(day))
tips <- within(tips, sex <- factor(sex, levels = c("Male","Female")))
with(tips, levels(sex))

p <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
p2 <- p + facet_grid(sex ~day )
p2
  • 修改后效果


    facet_v1

后记

今天无后记哈哈!
要是了解其他分面技巧,还请参考查阅其他更多资料啊哈哈!!

回头又想了想,不只是分面图,其他涉及不连续标签,比如箱线图、柱状图啊等等之类的都可以这么设置呀!

PS:

三三两两 浑浑噩噩
愿岁月静好且可期

2019/12/13 12:03


  1. 红字参考 ↩

你可能感兴趣的:(ggplot2||分面图facet_grid()/facet_wrap()自定义标签顺序)