【问题标题】:Automatically placing of text in ggplot2在ggplot2中自动放置文本
【发布时间】:2020-11-09 08:38:10
【问题描述】:

我需要绘制很多变量。在每个图中,我想自动将来自线性回归模型的信息放在图的左上角。

以 mtcars 数据集为例,我想要一段我可以使用的代码,无论我使用什么变量,它都能从图表左上角的线性回归模型中得到 R2 和 p 值互相勾结。我已经制定了一个解决方案,我在标题中绘制了 R2 和 P,但由于我需要另一个标题,所以它不是最佳的。

ggplotRegression <- function (fit) {
  
  require(ggplot2)
  
  ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() +
    stat_smooth(method = "lm", col = "red") +
    labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 1),
                                 " P =",signif(summary(fit)$coef[2,4], 1)))
    }

disp_vs_wt_cyl4 <- mtcars %>%
  filter(cyl=="4") 

ggplotRegression(lm(disp ~ wt, data = disp_vs_wt_cyl4)) +
  geom_point(size = 3.74, colour = "#0c4c8a") +
  theme_bw()

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    你可以在你的情节中使用annotation_custom,这样你就可以有一个单独的标题。在此示例中,我们允许将标题传递给您的函数:

    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)
    }
    

    所以我们可以这样做:

    disp_vs_wt_cyl4 <- mtcars %>% filter(cyl=="4") 
    
    ggplotRegression(lm(disp ~ wt, data = disp_vs_wt_cyl4), "My Title") +
      geom_point(size = 3.74, colour = "#0c4c8a") +
      theme_bw()
    

    【讨论】:

    • 哇,非常感谢,这将节省我的时间!使用您的代码,但是我得到一个图表,其中 iit 表示 NULL 而不是 disp ~wt。在 NULL 以下,我得到正确的 R2 和 p。你能解释一下你的函数是如何工作的吗?
    • 我认为as.expression 中有错字。 f 应该是 fit
    猜你喜欢
    • 2021-12-13
    • 2015-05-04
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    相关资源
    最近更新 更多