lkahtz
lkahtz

Reputation: 4796

geom_smooth is not spanning the whole range of data

The following code is drawing the smooth line. But it seems not span through the whole data range. Did I do anything wrong?

ggplot(mpg, aes(year, cty)) + geom_jitter() + geom_smooth(method = "lm", se = TRUE, span=3, fullrange=TRUE)

It gives me:

enter image description here

Upvotes: 2

Views: 1920

Answers (1)

beigel
beigel

Reputation: 1200

Your problem is with geom_jitter. Looking at the mpg dataset it appears there are only two years, 1999 and 2008. geom_jitter is making the range appear to be much wider than and it, but geom_smooth only draws a line in the range of the data. For example, using

ggplot(mpg, aes(year, cty)) + geom_point() + geom_smooth(method = "lm", se = TRUE, span=3, fullrange=TRUE)

gives us a plot like this instead

enter image description here

geom_jitter is jittering not just the y values (cty) but also the x values (year) which makes it appear as though the date range of the data is wider than it actually is. Since geom_smooth only interpolate inside the range, it doesn't span the whole plot like you want.

Upvotes: 7

Related Questions