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

I make a very wide graph, which when output as a PNG file takes several thousand pixels along the x axis; There are about 20 years of daily data. (This may or may not be considered good practice, but it is for my own use and not for publication.) Because the chart is so wide, the y axis disappears from view when you scroll the chart. Accordingly, I want to add labels to the chart at 2-year intervals to show the y-axis values. The resulting diagram looks like the one shown below, except that in the interest of compactness, I used only 30 days of fake data and put labels about every 10 days:

labelling plot with y-axis values ​​in gggplot2

This works more or less as needed, but I wonder if there is any better way to approach it, as in this diagram (see the following code). I have a column for each of the three Y axis values ​​120, 140, and 160. Real data has many more levels, so I get 15 geom_text calls to put everything in the chart area.

Q. Is there an easier way to plan all 20 odd dates, with 15 labels per day, right on the chart?

require(ggplot2)

set.seed(12345)
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)

print(p)
+5
source share
1 answer

ggplot2 loves the data to be in a long format, so melt()entering text in a long format allows you to make one call geom_text():

require(reshape2)
mytext.m <- melt(mytext, id.vars = "mydate")

Then your build command:

ggplot(data = mydf) +
  geom_line(aes(x = mydf$mydate, y = mydf$price), colour = 'red', size = 0.8) +
  geom_text(data = mytext.m, aes(x = mydate, y = value, label = value), size = 4)
+7
source

All Articles