Search code examples
rggplot2labelgeom-textline-plot

Label the points as date in the proper format in ggplot in R


I am plotting a line chart using ggplot2 in R. I want to name the points above a certain threshold in the proper date format.

My code for plotting the graph is:

ggplot(DateSubset1, aes(TimeStamp)) + 
    geom_line(aes(y = CPU, colour = "Orange")) + 
    geom_line(aes(y = MEM), colour = "Black")+
    scale_x_datetime(date_break = "1 days")+
    geom_point(aes (x= TimeStamp, y=CPU), size = 1,colour = "Purple", 
        subset(DateSubset1, CPU>25 ))+
    geom_point(aes (x= TimeStamp, y=MEM), size = 1,colour = "Blue", 
        subset(DateSubset1, MEM>10 ))+
    scale_y_continuous(breaks = c(5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80))

My Graph looks like this:

enter image description here

I want to label these points (which are above a certain threshold) with proper date format as my dataset has. I have tried

geom_text(aes(y=CPU, label= ifelse(CPU>25, TimeStamp, '')))

Using this my graph looks like:

enter image description here And

geom_text(aes(y= CPU,label= ifelse(CPU>25, format(TimeStamp), format = 
"%y%m%d %h%m%s",'')))

And

geom_text(aes(y= CPU, label=ifelse(CPU>25, as.Date(TimeStamp), '')))

And

geom_text(aes(y= CPU, label=ifelse(CPU>25, as.Date.POSIXct(TimeStamp), '')))

String of dataset:

data.frame':    
1420 obs. of  3 variables:
$ TimeStamp: POSIXct, format: "2017-06-28 07:03:02" "2017-06-28 07:06:01" 
"2017-06-28 07:09:01" ...
$ CPU      : num  0.9 0.8 12.2 3.7 2.3 1.7 1.4 1.1 1 0.9 ...
$ MEM      : num  1.7 1.8 1.5 1.8 1.8 1.8 1.9 1.9 1.9 2.1 ...

The sample Data looks like:

TimeStamp                CPU   MEM
2017-06-28 07:03:02      0.9   1.7
2017-06-28 07:06:01      0.8   1.8
2017-06-28 07:09:01      12.2  1.5
2017-06-28 07:12:01      3.7   1.8
2017-06-28 07:15:01      2.3   1.8

Solution

  • OK, try this code:

    zz = '
       CPU   MEM
       0.9   1.7
       0.8   1.8
       12.2  1.5
    '
    
    df <- read.table(text = zz, header = TRUE)
    df
    
    TmS = c("2017-06-28 07:03:02", "2017-06-28 07:06:01", "2017-06-28 07:09:01")
    df = cbind(TmS, df)
    df$TmS = as.character(df$TmS)
    
    label = as.character(ifelse(df$CPU>10, df$TmS, ''))
    df$TmS = as.POSIXct(df$TmS)
    
    
    ggplot(df, aes(TmS)) + 
      geom_line(aes(y = CPU, colour = "Orange")) + 
      geom_line(aes(y = MEM), colour = "Black")+
      scale_x_datetime(date_break = "1 days")+
      geom_point(aes (x= TmS, y=CPU), size = 1,colour = "Purple", 
                 subset(df, CPU>10))+
      geom_point(aes (x= TmS, y=MEM), size = 1,colour = "Blue", 
                 subset(df, MEM>1.5))+
      scale_y_continuous(breaks = c(5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80))+
      geom_text(aes(y= CPU, label=label))