geom_smooth很好,很大程度上是因为它平均了很多变化.但是,正因为如此,当缩小时,很难看出它在x轴上的变化情况.我正在制作大约1000张图,我需要ggplot2放大coord_cartesian.但是,每个图形都有不同的缩放限制.有没有办法我可以要求ggplot2放大以适应光滑?我对放大geom_smooth线和geom_smooth线加上SE阴影区的解决方案感兴趣.
例如,我有兴趣知道我怎么能这样做:
ggplot(data=mtcars, aes(y=qsec,x=wt)) + geom_point() + geom_smooth()
Run Code Online (Sandbox Code Playgroud)
进入这样的事情:
ggplot(data=mtcars, aes(y=qsec,x=wt)) + geom_point() + geom_smooth() + coord_cartesian(ylim = c(15,20))
Run Code Online (Sandbox Code Playgroud)
没有明确指定限制.
手动调整平滑模型可以更灵活地实现此类和其他类型的自定义.对于大多数项目,我开始使用内联接口,但是当我需要其他调整时,通常最终不得不切换到手动计算.
另见Hadley的书中的§9.1.1.
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)
Run Code Online (Sandbox Code Playgroud)

但是,这仍然不适用于facet,因为您只能指定,例如scales='free',而不是直接指定实际限制.