更改切面包装中切面的位置(按年份排序)

我想更改ggplot Boxplot的顺序和实验室。 这是我到目前为止的内容:

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","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,l = 0)))  

这是我的情节

更改切面包装中切面的位置(按年份排序)

我想更改不同构面的位置。 第一排2017年5月8日 第二排2018年5月9日

我在facet_wrap()中尝试了as.table = F,但仍然无法获得正确的顺序。

第二,我想更改标签。 在x轴下方,我想要月份(05-08 / 09),并在大标签的每一行上方,并带有年份(2017/2018)。

我搜索了数小时的所有内容,但找不到解决方案。我也尝试了fact_grid,但没有得到我想要的结果

谢谢!

tongzhi122015528 回答:更改切面包装中切面的位置(按年份排序)

您需要更改year_month的级别,好吧,我们首先创建一个函数来生成您的绘图,请注意,我包括一个facet_order,通过它可以对您的year_month进行重新调整:

/about

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

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","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,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)

enter image description here

一种“转置”您的级别的快速方法:

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

enter image description here

本文链接:https://www.f2er.com/2922739.html

大家都在问