rggplot2

Adding a general abline in log-log ggplot2


I am trying to add a line to separate part of data in ggplot2. Following this thread: Adding linear model abline to log-log plot in ggplot

I tried

d = data.frame(x = 100*rlnorm(100), y = 100*rlnorm(100))
ggplot(d, aes(x, y)) + geom_point() + 
  geom_abline(intercept = 100, slope = -1, col='red') +
  scale_y_log10() + scale_x_log10()

but it did not plot the line. Note that the old plot approach got the line alright:

plot(d$x, d$y, log='xy')
abline(a = 100, b=-1, col='red', untf=TRUE)

Solution

  • This may not be the most elegant solution, but I usually define a separate data frame for predictions when I'm adding them to plots. I know that it's quicker in a lot of ways to add the model specification as part of the plot, but I really like the flexibility of having this as a separate object. Here's what I've got in mind in this case:

    d = data.frame(x = 100*rlnorm(100), y = 100*rlnorm(100))
    
    p = ggplot(d, aes(x,y)) + geom_point() + scale_x_log10() + scale_y_log10()
    
    pred.func = function(x){
      100 - x
    }
    
    new.dat = data.frame(x = seq(from = 5, to = 90))
    new.dat$pred = pred.func(new.dat$x)
    
    p + geom_line(aes(x = x, y = pred), data = new.dat, col = "red")
    

    enter image description here