11

This question is similar to this one: Use geom_smooth with transformed y

In fact, it's the same one, it's just that the solution provided there no longer works.

What I want to do is plot a geom_smooth that has log(y) on the y side of the formula. If done directly in the formula argument, it gives a strange result. So, I will use the same example used in the question that I mentioned:

#This works:
 myplot <- qplot(speed, dist, data=cars)
(myplot + geom_smooth(method="lm", formula=y~log(x)))

#does not work
(myplot + geom_smooth(method="lm", formula=log(y)~x))

#no longer works:
(myplot + geom_smooth(method = "glm", formula = y~x,
                  family = gaussian(link = 'log')))

What I am after is a line like this:

myplot + geom_line(aes(x=speed, y=exp(predict(lm(log(dist)~speed)))))
3
  • are you still there OP?
    – Hack-R
    Dec 16, 2016 at 19:00
  • If the built-in help pages are cumbersome to wade through docs.ggplot2.org/current/# has the latest info for ggplot2 and it's almost 100% necessary to hit that for anything but the most basic plots if you're upgrading from an older version these days. many major, brekaing API changes.
    – hrbrmstr
    Dec 16, 2016 at 19:17
  • Hi, so I checked it, but couldn't find the right answer, because of the removal "family" argument. But I'll save the link here for future reference! Thanks! Dec 17, 2016 at 1:10

1 Answer 1

16

Yes, you're right, it seems the necessary syntax has changed a bit:

(myplot + geom_smooth(method = "glm", formula = y~x,
                      method.args = list(family = gaussian(link = 'log'))))

enter image description here

3
  • 1
    Yes! I could swear I had tried messing with the method.args argument, but couldn't figure it out properly. This is working now. Thanks man! Dec 17, 2016 at 1:13
  • 2
    I was using method = "lm" instead of "glm". Gotta pay attention on that! Dec 17, 2016 at 1:21
  • 3
    Why is it that the log link works, but not formula = 'log(y) ~ log(x)'? Jun 9, 2020 at 3:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.