【问题标题】:Facet-wrap in ggplot with function带有功能的ggplot中的Facet-wrap
【发布时间】:2021-02-22 03:45:30
【问题描述】:

@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, "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")

另外,我真的不明白代码的作用?

【问题讨论】:

  • 我想它应该是facet_wrap(~cyl, scales = "free") 虽然我不确定你要绘制什么。在示例中,您已将子集划分为 cyl==4
  • hm,谢谢你的建议,但我实际上得到了同样的错误:至少一层必须包含所有分面变量:cyl
  • 是的,@StupidWolf,你是对的,原来的问题是一个错字,但现在已经更正了。谢谢
  • 您能简要解释一下您要绘制的内容吗?不同子集的拟合度相同?
  • 您收到该错误是因为fit$model 不包含cyl... 这不是您可以即插即用的功能

标签: r ggplot2 tidyverse facet-wrap


【解决方案1】:

您遇到错误是因为该函数依赖于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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多