【问题标题】:Add p-value to ggplot without creating a lm-obejct separately在不单独创建 lm 对象的情况下将 p 值添加到 ggplot
【发布时间】:2019-07-01 20:40:41
【问题描述】:

我必须创建大量(100 多个)线性模型的 ggplots。我想将 p 值(可能还有 R2)添加到每个图中。我知道使用ggpmisc 可以做到这一点。在这里,我使用stat_fit_glance 来添加 p 值。我的“问题”是这两个都需要我先运行lm 才能插入为公式= my_lm。

由于我必须创建大量绘图,我想知道是否有一种方法可以避免首先创建 lm 对象,而在生成 ggplot 时简单地计算它?我可以使用stat_compare_means 对箱线图进行 t 检验,并且真的希望能找到一种方法来使用 lm 来实现。

我的代码如下所示。我希望能够跳过第一行代码:

my_lm <- lm(y ~ x)


ggplot(data = complete, aes(x= x, y = y))+  
geom_point()+
theme_classic()+
geom_smooth(method = "lm")+
labs(x="Ellenberg F", y = "Species richness")+
stat_fit_glance(method = 'lm',
              method.args = list(data = complete, formula = my_lm),
              geom = 'text',
              aes(label = paste("p-value = ", signif(..p.value.., digits = 4), sep = "")),
              label.x = 8.5, label.y = 25, size = 3)

我试过简单地把公式 = y ~ x 没有运气。

【问题讨论】:

  • 我强烈警告不要运行 100 多个线性模型并报告每个 p 值,分析的目的是什么?

标签: r ggplot2 ggpmisc


【解决方案1】:

ggpmisc::stat_fit_glance的帮助下:method.args = list(formula = y ~ x)
这意味着您不需要先运行lm
您只能指定线性模型的公式。

library(ggpmisc)
set.seed(1)
n <- 100
x <- 8+rnorm(n)
y <- 11+x+2*rnorm(n)
complete <- data.frame(x, y)

summary(lm(y~x))
ggplot(data = complete, aes(x= x, y = y))+  
geom_point()+
theme_classic()+
geom_smooth(method = "lm")+
labs(x="Ellenberg F", y = "Species richness")+
stat_fit_glance(method = 'lm',
       method.args = list(formula = y ~ x),  geom = 'text', 
       aes(label = paste("p-value=", signif(..p.value.., digits = 4), 
                      "   R-squared=", signif(..r.squared.., digits = 3), sep = "")),
       label.x = 8.5, label.y = 25, size = 5)

【讨论】:

  • 执行此操作时,我收到“提供给连续刻度的离散值”错误。任何想法如何解决这个问题?
  • @Skumin 我现在测试了上面的代码,它运行没有错误。您使用的是相同的数据集还是不同的数据集?
猜你喜欢
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-28
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 2016-03-13
相关资源
最近更新 更多