@Allan Cameron帮助我编写了一段代码,当我绘制两个变量时,它会自动将R2和p值(来自LM)放在图形的左上角。
然而,我不能让它与facet_wrap一起工作。例如,在mtcar数据集中,如果我想要对disp绘制wt,我可以这样做,但如果我想要使用facet_wrap为每个柱面组(例如4、6、8)绘制一幅图,则会收到以下错误消息
At least one layer must contain all faceting variables: `cyl`.
* Plot is missing `cyl`
* Layer 1 is missing `cyl`
* Layer 2 is missing `cyl`
* Layer 3 is missing `cyl`
* Layer 4 is missing `cyl`以下是代码
ggplotRegression <- function (fit, title) {
require(ggplot2)
lab <- grid::textGrob(label = paste0(
as.character(as.expression(fit$call$formula)), "\n",
"Adj R\u00b2 = ",
signif(summary(fit)$adj.r.squared, 1),
", p = ", signif(summary(fit)$coef[2,4], 1)),
x = unit(0.05, "npc"),
y = unit(0.9, "npc"), just = "left",
gp = grid::gpar(size = 14, fontface = "bold"))
ggplot(fit$model, aes_string(x = names(fit$model)[2],
y = names(fit$model)[1])) +
ggtitle(title) +
geom_point() +
stat_smooth(method = "lm", col = "red") +
annotation_custom(lab)
}
ggplotRegression(lm(disp ~ wt, data = mtcars), "My Title") +
geom_point(size = 3.74, colour = "#0c4c8a") +
theme_bw()+
facet_wrap(vars(cyl), scales = "free")另外,我也不太明白代码是做什么的?
发布于 2020-11-10 18:09:46
您会遇到错误,因为该函数依赖于fit$model,如果您将lm(disp ~ wt, data = mtcars)输入到数据中,您可以看到cyl不再位于ggplot对象中:
fit = lm(disp ~ wt, data = mtcars)
head(fit$model)
disp wt
Mazda RX4 160 2.620
Mazda RX4 Wag 160 2.875
Datsun 710 108 2.320
Hornet 4 Drive 258 3.215
Hornet Sportabout 360 3.440
Valiant 225 3.460@Allan为您提供的基本上是编辑1个绘图并在文本中插入。如果你想在不同的数据子集上拟合三个线性模型,应该是这样的:
library(ggpmisc)
library(ggplot2)
formula = y~x
ggplot(mtcars, aes(wt, disp)) +
geom_point() +
geom_smooth(method = "lm",formula=formula) +
facet_wrap(~cyl, scales = "free")+
stat_poly_eq(
aes(label = paste(stat(adj.rr.label), stat(p.value.label),sep = "*\", \"*")),
formula = formula, parse = TRUE,size=3)

https://stackoverflow.com/questions/64764926
复制相似问题