Skip to Content

R: In ggplot, how to add multiple text labels on the y-axis for each of multiple dates on the x-axis

I am making a very wide chart that, when output as a PNG file, takes up several thousand pixels in the x-axis; there is about 20 years of daily data. (This may or may not be regarded as good practise, but it is for my own use, not for publication.) Because the chart is so wide, the y-axis disappears from view as you scroll through the chart. Accordingly I want to add labels to the plot at 2-yearly intervals to show the values on the y-axis. The resulting chart looks like the one below, except that in the interests of keeping it compact I have used only 30 days of fake data and put labels roughly every 10th day:

This works more or less as required, but I wonder if there is some better way of approaching it as in this chart (see code below) I have a column for each of the 3 y-axis values of 120, 140 and 160. The real data has many more levels, so I would end up with 15 calls to geom_text to put everything on the plot area.

Q. Is there a simpler way to splat all 20-odd dates, with 15 labels per date, on to the chart at once?

mydf <- data.frame(mydate = seq(as.Date('2012-01-01'), as.Date('2012-01-31'), by = 'day'),
                     price = runif(31, min = 100, max = 200))
mytext <- data.frame(mydate = as.Date(c('2012-01-10', '2012-01-20')),
                col1 = c(120, 120), col2 = c(140,140), col3 = c(160,160))
p <- ggplot(data = mydf) +
    geom_line(aes(x = mydf$mydate, y = mydf$price), colour = 'red', size = 0.8) +
    geom_text(data = mytext, aes(x = mydate, y = col1, label = col1), size = 4) +
    geom_text(data = mytext, aes(x = mydate, y = col2, label = col2), size = 4) +
    geom_text(data = mytext, aes(x = mydate, y = col3, label = col3), size = 4)