Plot dates on the x axis and time on the y axis with ggplot2

試著忘記壹切 提交于 2019-11-27 23:05:57

There are two steps required:

  • Extract the time element from the POSIXct object. You can do that with some lubridate extractor functions and a bit of arithmetic, or by subtracting as.Date(dttm) from dttm. I show both ways.
  • Add a date-time y-axis and specify a suitable formatter

Two alternative ways to extract the time from a POSIXct object:

dropDate <- function(x){
  3600*hour(x)+60*minute(x)+second(x)
}

dropDate2 <- function(x){
  as.numeric(x - as.Date(x))
}  

You may also wish to specify explicit labels for the axes:

qplot(day(dttm), dropDate(dttm)) + 
    scale_y_datetime(format="%H:%M:%S") + 
    xlab("Day") + ylab("Hour")


There are more examples of this type of scale in ?scale_datetime, which will point you to ?strptime for an explanation of the date and time formatting codes.

You can tweak the date axes using scale_datetime. The examples at the end are quite illustrative.

http://had.co.nz/ggplot2/scale_datetime.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!