如何解决具有功能的ggplot中的facet换行
@Allan Cameron帮助我编写了一个代码,当我绘制两个变量时,该代码自动将R2和p值(来自LM)放置在图形的左上角。
但是我无法使其与facet_wrap一起使用。例如,在mtcars数据集中,如果我想对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,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")
我还不太了解代码的作用?
解决方法
由于函数依赖于fit$model
,而您遇到错误,并且如果将lm(disp ~ wt,data = mtcars)
输入数据,则可以看到ggplot对象中不再包含cyl:
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。