2012-04-25 15 views
2

私はggplot2を使って、y-スレッショルドより大きいすべてのy-値にアノテートしたいと思います。ggplotで極値をラベル付け/注釈する最も簡潔な方法は?

plot(lm(y~x))とすると、基本パッケージを使用すると、自動的にポップアップする2番目のグラフは、残差対適合、3番目はqqplot、4番目はスケール位置です。これらのそれぞれは、対応するX値を隣接する注釈としてリストすることによって、極端なY値を自動的にラベル付けします。私はこのようなものを探しています。

ggplot2を使用してこの基本デフォルト動作を達成する最も良い方法は何ですか?

+0

'強化()'関数は有用かもしれません。 Whickhamのggplot2本のコピーを入手できる場合は、9.3節(169-175ページ)を参考にしてください。 172ページで、Wickhamは、「強化されたデータセットを使用することで、plot.lm()によって生成されたプロットを簡単に再作成でき、さらに良いものにすることができます。」 –

+0

注釈を含むグラフを追加しました'極端な' y値 –

答えて

7

は、あなたのニーズに合わせて、このから何かを取ることができるかもしれないscale_area()

の代わりにscale_size_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

関連する問題