自动排除异常值以在ggplot2中重新缩放y轴,而无需重新计算y变量

时间:2019-03-28 20:00:49

标签: r ggplot2 plot

我正在寻找一种优雅,自动的方法,使用由ylimgeom_函数中的美学产生的计算变量来设置图的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() 

Figure 1: Poor resolution for majority of data due to the presence of two outliers

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

Figure 2: Good resolution of majority of data due to zooming in of axes to exclude outliers

问题

问题是我需要自己计算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) ) )

0 个答案:

没有答案