我正在寻找一种优雅,自动的方法,使用由ylim
或geom_
函数中的美学产生的计算变量来设置图的stat
,不要采取任何措施回到输入到ggplot
例如,这在自动生成不包含离群值的图的放大视图时非常有用,以使轴的比例对于离群值不会太大。
df = data.frame(a=1:100 , b = rnorm(100))
# add outlier
df <- rbind(df , data.frame(a=50,b=c(-70,80)) )
# naive plot: the scale of the y axis is very large because of the outliers and you therefore have poor resolution for the bulk of the data.
gp <- ggplot( data = df , aes(x=a,y=b) ) + geom_point()
# zoom-in so that the y axis limits are appropriate for the bulk of the data, i.e. excluding outliers
gp + coord_cartesian(ylim = quantile( df$b , c(0.02,0.98) ) )
问题是我需要自己计算y
变量以提供给quantile
函数以设置ylim
。
有时,赋予计算的y
变量的值可以是平凡的或复杂的,例如涉及一些公式或数据子集等。
因此,如果我可以将y
语句中的aes
变量传递给quantile
语句中的coord_cartesian
函数,那将非常有用。
以下引发错误消息:
gp + coord_cartesian(ylim = quantile( y , c(0.02,0.98) ) )
gp + coord_cartesian(ylim = quantile( ..y.. , c(0.02,0.98) ) )
gp + coord_cartesian(ylim = quantile( stat(y) , c(0.02,0.98) ) )