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

后端 未结 2 960
余生分开走
余生分开走 2020-12-06 06:50

I have read in a series of 37 dates and times that an event happened. It is now sitting as a POSIXlt object. I want a graphic representation of the times that the events hap

相关标签:
2条回答
  • 2020-12-06 07:16

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

    enter image description here


    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.

    0 讨论(0)
  • 2020-12-06 07:16

    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

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