在使用ggplot2和 ggfortify这两个R 包时,如何消除警告信息
我正在绘制残差图,用以检查使用ggplot2和 ggfortify R包的一般线性模型的假设,但我一直收到警告信息,不确定如何去除它们。图像没问题,但这些警告让我有些困扰。
我正在运行的R 代码如下:
diag.rs2292334_auc_w <- autoplot(rs2292334_auc_w,which=1:6,ncol=3) + theme(plot.margin = unit(c(1, 1, 1, 1), "cm"), panel.background = element_blank(), axis.line = element_line(color = "black"),axis.title = element_text(size = 16, color = "black"),axis.text.x = element_text(size = 16, color = "black"),axis.title.x = element_text(margin= margin(t=10)),axis.text.y = element_text(size = 16),axis.title.y = element_text(margin = margin(r = 10)),axis.ticks.x = element_blank())
应该对上述代码做哪些修改以避免下方的警告信息?:
Warning messages:
1: `fortify(<lm>)` was deprecated in ggplot2 4.0.0.
ℹ Please use `broom::augment(<lm>)` instead.
ℹ The deprecated feature was likely used in the ggfortify package.
Please report the issue at <https://github.com/sinhrks/ggfortify/issues>.
This warning is displayed once per session.
Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
generated.
2: `aes_string()` was deprecated in ggplot2 3.0.0.
ℹ Please use tidy evaluation idioms with `aes()`.
ℹ See also `vignette("ggplot2-in-packages")` for more information.
ℹ The deprecated feature was likely used in the ggfortify package.
Please report the issue at <https://github.com/sinhrks/ggfortify/issues>.
This warning is displayed once per session.
Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
generated.
3: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.
ℹ The deprecated feature was likely used in the ggfortify package.
Please report the issue at <https://github.com/sinhrks/ggfortify/issues>.
解决方案
我认为第一步最简单,就是用 suppressWarnings() 来抑制它。然而,这有时会过于强力,完全掩盖其他本来可能有用的信息性警告。
我建议再进一步,只抑制那些警告。这可以通过 withCallingHandlers(tryCatch 的同类)和 invokeRestart("muffleWarning") 来实现。
suppressWarnings_ggfortify <- function(...) {
withCallingHandlers(
...,
warning = function(wrn) {
cnd <- conditionMessage(wrn)
if (grepl("(`fortify\\(<lm>\\)`|`aes_string\\(\\)`) was deprecated in ggplot2", cnd) ||
grepl("Using `size` aesthetic for lines was deprecated in ggplot2", cnd)) {
invokeRestart("muffleWarning")
}
wrn
}
)
}
# using the example from Rui's answer
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl","Trt"))
weight <- c(ctl, trt)
lm.D9 <- lm(weight ~ group)
suppressWarnings_ggfortify(autoplot(lm.D9, which = 1:6, ncol = 3))
如果不仅仅是 ggfortify 在遇到弃用警告,或者还有更多情况,你可以把它的特异性稍微放宽一些,将 warning= 函数的条件改成只有 grepl("deprecated in ggplot2", cnd),尽管我个人认为尽早了解弃用信息更好。例如,我可能在一个生成的报告中使用上述函数,但在控制台上不这样做;这意味着我生成的报告不会包含它,但我仍然会在控制台得到提醒。仅代表我的一点小小建议 :-)
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。