R语言 变更刻面折绕中刻面的位置(依年份排序)

mbjcgjjk  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(98)

我想改变我的ggplot箱线图的顺序和实验室。这是我目前所拥有的:

ggplot(total_nr_obj_week_corr.3, aes(x=distance, y=n)) +
  stat_boxplot(geom = "errorbar")+
  geom_boxplot()+
  facet_wrap(~year_month, strip.position = "bottom",scales = "free", nrow=2)+
  scale_y_continuous(expand = c(0,0),limits = c(0, 70), breaks = seq(0, 80, by = 10)) +
  scale_x_discrete(limits = c("0", "5","10", "15","20"), breaks = c("0", "5","10", "15","20"))+
  theme(strip.placement="outside", 
        strip.background = element_rect(color="black",
fill="white",size = rel(1)),
        axis.title.x = element_text(margin = margin(t = 10, r = 0 , b = 0, l = 0)),
        axis.title.y = element_text(margin = margin(t = 0, r = 10 , b = 0, l = 0)))

"这是我的地盘"

我想将不同刻面的位置更改为以下位置:

  • 第一排2017年05月8日
  • 第二排2018年05月9日

我在facet_wrap()中尝试了as.table = F,但仍然没有得到正确的顺序。其次,我想更改标签。在x轴下方,我想要月份(05-08/09),在每行上方的大标签上,每行都有年份(2017/2018)。
我在谷歌上搜索了几个小时,但没有找到解决方案。我也尝试了X1 M3 N1 X,但这并没有给予我想要的结果。
感谢您发送编修。

kknvjkwl

kknvjkwl1#

你需要改变year_month的级别,首先我们创建一个函数来生成你的图,注意我包含了一个facet_order,我用它来重新调整year_month的级别:

func=function(DA,facet_order){

ggplot(data=DA, aes(x=distance, y=n)) +
  stat_boxplot(geom = "errorbar")+
  geom_boxplot()+
  facet_wrap(~factor(year_month,levels=facet_order), strip.position = "bottom",scales = "free", nrow=2)+
  scale_y_continuous(expand = c(0,0),limits = c(0, 70), breaks = seq(0, 80, by = 10)) +
  scale_x_discrete(limits = c("0", "5","10", "15","20"), breaks = c("0", "5","10", "15","20"))+
  theme(strip.placement="outside", 
        strip.background = element_rect(color="black",
fill="white",size = rel(1)),
        axis.title.x = element_text(margin = margin(t = 10, r = 0 , b = 0, l = 0)),
        axis.title.y = element_text(margin = margin(t = 0, r = 10 , b = 0, l = 0))) 
}

我模拟了一些看起来像你的数据的东西:

library(ggplot2)

DATES = c("2017 05","2017 06","2017 07","2017 08",
 "2018 05","2018 06","2018 07","2018 08","2018 09")

total_nr_obj_week_corr.3 = lapply(DATES,function(i){
  data.frame(
  distance=factor(rep(seq(0,20,by=5),each=10)),
  n = rnbinom(50,mu=20,siz=1),
  year_month = i
)
})

total_nr_obj_week_corr.3 = do.call(rbind,total_nr_obj_week_corr.3)

现在,如果我们使用原始水平,我们会得到与您的图类似的结果:

lvl=levels(total_nr_obj_week_corr.3$year_month)
func(total_nr_obj_week_corr.3,lvl)+ggtitle("original levels")

一种“调换”电平的快速方法:

NCOL=5
NROW=2
LAY_FACET = matrix(NA,ncol=NCOL,nrow=NROW)
LAY_FACET[1:length(lvl)]=lvl
new_lvl = na.omit(c(t(LAY_FACET)))

func(total_nr_obj_week_corr.3,new_lvl)+ggtitle("new levels")

相关问题