2012-04-25 116 views
2

我想使用ggplot2注释大于y阈值的所有y值。用ggplot标记/注释极值的简洁方法?

当您使用基础软件包plot(lm(y~x))时,自动弹出的第二个图形是残差vs拟合,第三个图形是qqplot,第四个图形是比例位置。其中的每一个都会通过将相应的X值列为相邻注释来自动标记您的极端Y值。我正在寻找这样的东西。

使用ggplot2实现这种基本默认行为的最佳方式是什么?

+0

的'强化()'函数可能是有用的。如果你能得到Whickham的ggplot2书的副本,9.3节(第169-175页)应该会有所帮助。 Wickham在第172页写道:“通过使用强化的数据集,我们可以轻松地重新创建plot.lm()生成的图,甚至更好,我们可以根据我们的需要来调整它们。”# – 2012-04-25 08:21:12

+0

我添加了一个包含注释的图表为'极端'y值 – 2012-04-25 21:58:22

回答

7

更新scale_size_area()代替scale_area()

你也许能够把一些东西从这个满足您的需求。

library(ggplot2) 

#Some data 
df <- data.frame(x = round(runif(100), 2), y = round(runif(100), 2)) 

m1 <- lm(y ~ x, data = df) 
df.fortified = fortify(m1) 

names(df.fortified) # Names for the variables containing residuals and derived qquantities 

# Select extreme values 
df.fortified$extreme = ifelse(abs(df.fortified$`.stdresid`) > 1.5, 1, 0) 

# Based on examples on page 173 in Wickham's ggplot2 book 
plot = ggplot(data = df.fortified, aes(x = x, y = .stdresid)) + 
geom_point() + 
geom_text(data = df.fortified[df.fortified$extreme == 1, ], 
    aes(label = x, x = x, y = .stdresid), size = 3, hjust = -.3) 
plot 

plot1 = ggplot(data = df.fortified, aes(x = .fitted, y = .resid)) + 
    geom_point() + geom_smooth(se = F) 

plot2 = ggplot(data = df.fortified, aes(x = .fitted, y = .resid, size = .cooksd)) + 
    geom_point() + scale_size_area("Cook's distance") + geom_smooth(se = FALSE, show_guide = FALSE) 

library(gridExtra) 
grid.arrange(plot1, plot2) 

enter image description here

enter image description here