ggplot2 - 自动放大geom_smooth(使用coord_cartesian)

时间:2011-10-22 02:27:26

标签: r ggplot2

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()

这样的事情:

ggplot(data=mtcars, aes(y=qsec,x=wt)) + geom_point() + geom_smooth() + coord_cartesian(ylim = c(15,20))

未明确指定限制。

1 个答案:

答案 0 :(得分:7)

手动安装平滑模型可以更加灵活地实现此类和其他类型的自定义。对于大多数项目,我开始使用内联接口,但是当我需要进行其他调整时,通常最终不得不切换到手动计算。

另见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)

enter image description here

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