Plot time series (for 24 hours) in R

10,853

Solution 1

Convert to POSIXct first:

my$Time <- as.POSIXct(my$Time, format="%H:%M:%S")
ggplot(data=my, aes(x=my$Time,y=TD_Wait/1000)) + geom_point() 

enter image description here

ggplot takes care of the rest.

Solution 2

Here's a base graphics approach. You can use axis.POSIXct and axis.Date to plot POSIX* or Date axes, as shown.

d <- read.table(text='Time TD_Wait
18:24:45.776   12442
18:24:53.798   26799
19:10:32.963   14423
19:10:34.709   13592
19:10:38.056   13457
19:10:38.281   14063', header=TRUE)

d$Time <- as.POSIXct(d$Time, format="%H:%M:%S")
plot(d$Time, d$TD_Wait/1000, xaxt='n', pch=20, las=1, 
     xlab='Time', ylab='TD_Wait/1000')
axis.POSIXct(1, d$Time, format="%H:%M:%S")

enter image description here

Share:
10,853

Related videos on Youtube

user3006691
Author by

user3006691

Updated on July 12, 2022

Comments

  • user3006691
    user3006691 almost 2 years

    I have the following data frame:

    > head(my[,1:2])
                 Time TD_Wait
    96   18:24:45.776   12442
    97   18:24:53.798   26799
    1944 19:10:32.963   14423
    1945 19:10:34.709   13592
    1946 19:10:38.056   13457
    1947 19:10:38.281   14063
    
    > str(my)
    'data.frame':   25007 obs. of  2 variables:
     $ Time   : Factor w/ 253251 levels "00:00:00.586",..: 27991 28001 33296 33306 33319 33320 33341 33363 33383 33392 ...
     $ TD_Wait: int  12442 26799 14423 13592 13457 14063 11717 10026 10590 19372 ...
    

    I am unable to format the time labeling on the X-Axis when i try

    ggplot(data=my, aes(x=my$Time,y=TD_Wait/1000)) + geom_point() 
    

    as all the times are overlapping each other. I am confused on how to proceed with this. I tried changing the factor of Time but got nowhere with it.

    Is there a way clearly display the labeling of time on X-Axis on an hourly basis for a 24 hour period ?

  • user3006691
    user3006691 over 10 years
    Awesome, I'm so stupid I was playing around with POSIXct but was unsuccessful .... thanks you very much @BrodieG
  • BrodieG
    BrodieG over 10 years
    @user3006691, glad this helps. If this answers your question please consider marking it as answered.
  • user3006691
    user3006691 over 10 years
    a quick question.. when i did the plot for the entire data set, ggplot gives the date and time on the X-Axis as Feb 28 00:00 to Mar 1 00:00, but this data is actually from last week is there a way to avoid displaying the date ?