geom_smooth
is great, in large part because it averages out a lot of variation. However, because of this, it's difficult to see how it varies over the x-axis when it is zoomed out. I am producing about 1000 graphs where I need to have ggplot2
zoom in via coord_cartesian
. However, each graph would have different zoom limits. Is there a way I can ask ggplot2
to zoom in to fit the smooth? I am interested in solutions for both zooming in on just the geom_smooth
line and the geom_smooth
line plus SE shaded area.
For example, I would be interested in knowing how I could turn this:
ggplot(data=mtcars, aes(y=qsec,x=wt)) + geom_point() + geom_smooth()
into something like this:
ggplot(data=mtcars, aes(y=qsec,x=wt)) + geom_point() + geom_smooth() + coord_cartesian(ylim = c(15,20))
without explicitly specifying the limits.
Fitting your smoothing models manually gives you much more flexibility for attaining this and other types of customization. For most projects, I start off using the in-line interface, but then usually end up having to switch to manual calculation when I need other tweaks.
See also §9.1.1 in Hadley's book.
require(ggplot2)
# Fit smooth manually
fit = loess(qsec ~ wt, data=mtcars)
newx = data.frame(wt=with(mtcars, seq(min(wt), max(wt), len=100)))
pred = predict(fit, newdata=newx, se=T)
pred = cbind(wt=newx, qsec=pred$fit, se=pred$se.fit)
# Calculate limits based on extent of smooth geom
ylims = with(pred, c(floor(min(qsec-se)), ceiling(max(qsec+se))))
# Plot
dev.new(width=5, height=4)
ggplot(data=mtcars, aes(y=qsec, x=wt)) +
geom_point() +
geom_smooth(aes(ymax=qsec+se, ymin=qsec-se), data=pred, stat='identity') +
coord_cartesian(ylim = ylims)
However, this still doesn't work for facets because you can only specify, for example, scales='free'
, and not the actual limits directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With