Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 -- zooming in on geom_smooth automatically (using coord_cartesian)

Tags:

r

ggplot2

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.

like image 783
Xu Wang Avatar asked Oct 22 '11 02:10

Xu Wang


1 Answers

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)

enter image description here

However, this still doesn't work for facets because you can only specify, for example, scales='free', and not the actual limits directly.

like image 117
John Colby Avatar answered Sep 22 '22 01:09

John Colby