问题描述
geom_smooth
非常棒,主要是因为它平均出很多变化。但是,正因为如此,很难看出它在缩小时如何在X轴上变化。我制作了大约1000张图,需要通过 coord_cartesian
放大 ggplot2
。但是,每个图表都会有不同的缩放限制。有没有一种方法可以请求 ggplot2
来放大以适应平滑?我对缩放 geom_smooth
行和 geom_smooth
行加上SE阴影区域的解决方案感兴趣。 / p>
例如,我很想知道如何变成这样:
ggplot(data = mtcars,aes(y = qsec,x = wt))+ geom_point()+ geom_smooth()
变成这样的形式:
ggplot(data = mtcars,aes(y = qsec,x = )+ geom_point()+ geom_smooth()+ coord_cartesian(ylim = c(15,20))
手动拟合平滑模型为您获得更多的灵活性来实现此类和其他类型定制。对于大多数项目,我开始使用在线界面,但是当我需要其他调整时,通常最终不得不切换到手动计算。
另见§9.1 .1在Hadley的书中。 require(ggplot2)
#手动平滑放置
fit =黄土(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根据平滑几何的范围限制
ylims = with(pred,c(floor(min(qsec-se)),ceiling(max(qsec + se))))
#
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)
但是,这仍然不适用于facet,因为您只能指定 scales ='free',而不是直接的实际限制。
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.
这篇关于ggplot2 - 自动放大geom_smooth(使用coord_cartesian)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!