【问题标题】:Add p-value and R2 ggplot [follow-up]添加 p 值和 R2 ggplot [后续]
【发布时间】:2016-09-05 14:52:06
【问题描述】:

这是一个后续question。当我运行下面给出的代码时,我收到警告消息,我认为这是由于我的代码中没有方面的要求,而链接中提到的源代码包括方面。看看,请让我知道哪个部分需要修改。期待!

代码:

library(dplyr) 
library(ggplot2)
library(ggpmisc)

df <- diamonds %>%
  dplyr::filter(cut%in%c("Fair","Ideal")) %>%
  dplyr::filter(clarity%in%c("I1" ,  "SI2" , "SI1" , "VS2" , "VS1",  "VVS2")) %>%
  dplyr::mutate(new_price = ifelse(cut == "Fair", 
                                   price* 0.5, 
                                   price * 1.1))


p <- ggplot(df, aes(x,y, color=factor(cut))) 
p <- p + stat_smooth(method = "lm", formula = y ~ x-1, size = 1, level=0.95) 
p <- p + geom_point(alpha = 0.3) 
p <- p + stat_poly_eq(aes(label = paste(..rr.label..)),
                      label.x.npc = "right", label.y.npc = 0.15, formula = formula, 
                      parse = TRUE, size = 3) + 
          stat_fit_glance(method = 'lm', method.args = list(formula = formula),
                      geom = 'text', aes(label = paste("P-value = ", 
                      signif(..p.value.., digits = 4), sep = "")),label.x.npc = 'right',
                      label.y.npc = 0.35, size = 3)
print(p)

警告信息:

1:stat_poly_eq() 中的计算失败: “闭包”类型的对象不是子集

2:stat_fit_glance() 中的计算失败: “闭包”类型的对象不是子集

【问题讨论】:

  • 请注意,如果您已经使用library(dplyr) 加载了dplyr,则当您从dplyr 调用函数时,无需在前面加上dplyr::(例如dplyr::filter 等) .

标签: r ggplot2


【解决方案1】:

简答:你需要添加

formula <- y ~ x

(或任何您定义的公式)在您调用ggplot 之前(即在读取p &lt;- ggplot(...) 的行之前。


A "closure" is a type of function in R. 所以警告消息“'closure' 类型的对象不是子集的”意味着您运行的任何代码都没有期望一个函数对象。

当我们仔细查看您的代码时,我们会在您对 stat_poly_eqstat_fit_glance 的调用中看到 formula = formula。注意formula是R中的一个函数。如果你没有单独定义一个formula对象,R会认为你指的是formula函数。 stat_poly_eq()stat_fit_glance() 抱怨是因为他们希望函数中的 formula 参数formula 类对象,而不是函数。

更一般地说,您不应该将公式命名为“公式”,因为这会造成混淆。你可以使用例如改为“模型”。

【讨论】:

  • 太好了,谢谢!我得到两个 R2 和 p 值。为什么 p 值为零?这也很奇怪,我尝试更改数字但仍然不适用于大多数列signif(..p.value.., digits = 4)
  • 那是因为对于您要拟合的模型,p 值非常小以至于接近于零。如果您安装了broom 软件包,请执行broom::glance(lm(y ~ x - 1, df)),您会看到它报告的 P 值为零。
  • 我应该在哪里提到broom::glance(lm(y ~ x - 1, df))?在p&lt;- ggplot(..)? 行之前
  • 您可以在定义df 后随时发出命令。 (注意df 本身是一个函数——它是 F 分布的密度函数——所以你可能不想把你的对象也称为“df”。)
  • 如果您有后续请开一个新问题; cmets 部分不是为扩展讨论而设计的。
猜你喜欢
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
  • 2021-11-20
  • 2020-11-10
  • 2021-11-12
  • 2021-10-22
相关资源
最近更新 更多