Most succinct way to label/annotate extreme values

2019-05-25 18:08发布

I'd like to annotate all y-values greater than a y-threshold using ggplot2.

When you plot(lm(y~x)), using the base package, the second graph that pops up automatically is Residuals vs Fitted, the third is qqplot, and the fourth is Scale-location. Each of these automatically label your extreme Y values by listing their corresponding X value as an adjacent annotation. I'm looking for something like this.

What's the best way to achieve this base-default behavior using ggplot2?

1条回答
淡お忘
2楼-- · 2019-05-25 18:42

Updated scale_size_area() in place of scale_area()

You might be able to take something from this to suit your needs.

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

查看更多
登录 后发表回答