rotating axis labels in date format

后端 未结 1 1453
半阙折子戏
半阙折子戏 2020-12-28 16:50

does anyone know how to rotate axis ticks in the date format with ggplot2? I want to get labels with \"Date-Month\" (ex. \"1985-5\") with a 45° angle on the x axis.

相关标签:
1条回答
  • 2020-12-28 17:15

    First, you should make column Date as date. As it do not have the day provided, you should add for example 01 to each date and convert them.

    data$Date<-as.Date(paste(data$Date,"-01",sep=""),format="%Y-%m-%d")
    

    To get correct placement of labels under x axis you should set not just angle= but also hjust=1 to ensure that end of the label is placed under the tick mark. Also theme_bw() should be placed before theme specification of axis texts.

    ggplot(data=na.omit(data), aes(x=Date, y=Ptot, group=Station))+
      geom_line()+
      facet_grid(Station~.)+
      scale_x_date(breaks = "month", labels=date_format("%Y-%m"))+
      xlab("Year")+
      ylab("Prec (mm)")+theme_bw()+
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题