0

Would it be possible to add a text label with the hour when each peak occurred in

ggplot(lynx.df, aes(time, V.lynx)) + 
  geom_line() + 
  stat_peaks(colour = "red") + 
  stat_peaks(geom = "text", colour = "red", vjust = -0.5) + 
  ylim(-100, 7300)

I copy here the head of the data file:

date,o3
1/8/2015 0:00,27.4
1/8/2015 1:00,31.6
1/8/2015 2:00,36
1/8/2015 3:00,25.2
1/8/2015 4:00,22.6
1/8/2015 5:00,28.9
1/8/2015 6:00,30.6
1/8/2015 7:00,39.5
1/8/2015 8:00,40.9
1/8/2015 9:00,40.6
1/8/2015 10:00,39.1
...

Thanks for your help

Pedro J. Aphalo
  • 5,796
  • 1
  • 22
  • 23

1 Answers1

1

Yes, adding the hour is possible if it is in the data. You need to supply a suitable format string. Using the example data you sent me privately one could use the following code.

library(readr)
library(dplyr)
library(lubridate)
library(ggplot2)
library(ggpmisc)

ozone.df <- read_csv("ggpmisc.csv", col_types = "cd")
ozone.df <- mutate(ozone.df, datetime = dmy_hm(date))
ggplot(ozone.df, aes(datetime, o3)) + geom_line() +
  stat_peaks(colour = "red", span = 21, ignore_threshold = 0.5) +
  stat_peaks(geom = "text", colour = "red", span = 21, ignore_threshold = 0.5,
             hjust = -0.1, x.label.fmt = "%H:%M", angle = 90) +
  ylim(0, 85)

I added some other tricks assuming that you are interested in daily peaks (span=21 uses a moving window of 21 observations to find the peaks). I also assumed that you are interested in local peaks only if they are in the upper half of the y-range of the observations. You asked for hours, I added also minutes to make it more readable. If you prefer to have just hours, then change “%H:%M” to “%H”.

Here is the resulting plot: enter image description here

Pedro J. Aphalo
  • 5,796
  • 1
  • 22
  • 23