r - 使用 ggplot 标记/注释极值的最简洁方法?

标签 r annotations ggplot2

我想使用 ggplot2 注释所有大于 y 阈值的 y 值。

当你plot(lm(y~x))时,使用基础包,自动弹出的第二张图是Residuals vs Fitted,第三张是qqplot,第四张是Scale-地点。这些中的每一个都会通过将相应的 X 值列为相邻注释来自动标记您的极端 Y 值。我正在寻找这样的东西。

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

最佳答案

更新 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

关于r - 使用 ggplot 标记/注释极值的最简洁方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10310728/

相关文章:

java - @SuppressWarnings 是否处理注释生成的警告?

r - 带有抖动地毯的直方图

r - 创建具有不同比例的累积分布曲线 (ECDF) 的 ggplot2 直方图

r - 向密度图添加百分位线

r - 来自 Stata 的 xtpcse - 如何在 R 中重写

r - qplot/ggplot 中带分数的直方图

r 派生指示变量

r - 算术运算符是否比算术函数更可取?

java - Intellij idea 显示错误警告

java - Guice 根据父实例注解注入(inject)不同的实例