2012-04-25 111 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