r - 在ggplot2中使用stat_poly_eq为每个方面指定公式

标签 r ggplot2 ggpmisc

我从here借用了此示例数据集:

# Load library
library(ggplot2)

# Load data
data(mtcars)

# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method="lm")
print(p)


在上面的代码中,所有方面的回归方法和公式均相同。如果要为构面(或面板)6指定公式,则可以从here使用以下代码:

# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
  smooth.call <- match.call()

  if(as.numeric(unique(data$PANEL)) == 6) {
    # Linear regression
    smooth.call[[1]] <- quote(lm)
    # Specify formula
    smooth.call$formula <- as.formula("y ~ log(x)")
  }else{
    # Linear regression
    smooth.call[[1]] <- quote(lm)
  }

  # Perform fit
  eval.parent(smooth.call)
}

# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth", se = FALSE)
print(p)


现在,如果我想向这些方面添加回归方程式:

# Load library
library(ggpmisc)
p + stat_poly_eq(formula = y ~ x,aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), 
    parse=TRUE,label.x.npc = "right")


然后,我应该怎么做才能指定面板6上显示的方程式和R2,它们可以匹配我之前指定的模型?参见下图,现在面板6具有自己的拟合模型,但是方程式标签没有。也许我们可以定义与ggplot2参数类似的函数?

enter image description here

最佳答案

您正在调用的custom.smooth函数似乎包含将公式定义为"y ~ log(x)"的行。因此,您还需要在您的stat_poly_eq函数中指定此函数,从而指定线性外观方程的多项式形状(但实际上是对数形式)。

即加:

p + stat_poly_eq(formula = y ~ log(x),
                     aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), 
                     parse=TRUE,label.x.npc = "right")

关于r - 在ggplot2中使用stat_poly_eq为每个方面指定公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48381672/

相关文章:

R | ggplot2 | (删除刻度线 + 删除面板边框)但保留轴线

r - 如何在 rmarkdown html_document 中对齐表格和绘图

r - 加速 gganimate 渲染

r - 通过行名和列名而不是数字来访问值

r - 如何使用 ggpmisc 的 stat_poly_eq 在方程中显示不同的 y 标签

r - 如何按定义的顺序将图像合并到一个文件中

r - 如何摆脱 geom_smooth 连续错误代码?

json - 将R字符对象写入JSON时如何去除\"

r - 用 ggpmisc 显示 nls 模型的方程