Date format for subset of ticks on time axis

前端 未结 1 1235
名媛妹妹
名媛妹妹 2021-02-10 09:52

Problem

I would like to format my X-axis (time) so that the weekends are clearly visible. I would like to display the date as well as the day of the wee

1条回答
  •  南笙
    南笙 (楼主)
    2021-02-10 10:34

    You can use your custom formater for labels also using breaks="1 day" argument, you just have to use function(x) after labels= and replace myDate$timestamp with x. This will also solve the third problem.

     + scale_x_date(breaks="1 day", 
          labels= function(x) paste(substr(format(x, "%a"),1,1),format(x, "%d"),sep="\n")) 
    

    Or you can make your transformation as seperate function and then use it for labels=.

    my_date_trans<-function(x) {
          paste(substr(format(x, "%a"),1,1),format(x, "%d"),sep="\n")
    }
    
    + scale_x_date(breaks="1 day",labels=my_date_trans)
    

    To change colors for labels you should use theme() and axis.text.x=. Here I using vector of colors that contains 6 time black and then red as your scale starts with Monday. Those colors are then repeated.

    ggplot() +
          geom_rect(data=rects, aes(xmin=saturdays, xmax=sundays,ymin=-Inf, ymax=Inf), alpha=0.1) +
          geom_line(data=myData, aes(x=timestamp, y=value, colour=variable,size=1)) + 
          geom_point(data=myData, aes(x=timestamp, y=value, colour=variable,size=2)) +
          scale_x_date(breaks="1 day",labels=my_date_trans)+
          scale_size_continuous(range = c(1.5,5), guide=FALSE)+
          theme(axis.text.x=element_text(color=c(rep("black",6),"red")))
    

    enter image description here

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