【问题标题】:Specifying formula for each facet using stat_poly_eq in ggplot2在 ggplot2 中使用 stat_poly_eq 为每个方面指定公式
【发布时间】:2018-01-22 12:30:17
【问题描述】:

我从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)

在上面的代码中,回归方法和公式在所有方面都是相同的。如果我们想为 facet (or panel) 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 参数类似的函数?

【问题讨论】:

  • 为什么不在 ggplot 之外拟合方程,并将结果绘制为 geom_line,方程文本绘制为 geom_text?没有理由在 ggplot 中做所有事情。
  • 没有一个答案能解决您的问题

标签: r ggplot2 ggpmisc


【解决方案1】:

您调用的函数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")

【讨论】:

  • 这会为其他方面产生正确的结果(即线性方程)吗?
  • 用x 替换custom.smooth 函数中的log(x) 和ggpmisc 包中的stat_poly_eq 函数。
  • @Lyngbakr 我不明白这个答案。我想针对不同方面使用不同的公式
【解决方案2】:

您可以单独更新面板 6 的公式(当然您也可以使用类似的功能更新所有面板,但这里不需要)

rename_panel_expression <- function(grb, panel, expr) {
  g <- grb$grobs[[panel + 1]]$children
  grb$grobs[[panel + 1]]$children[[grep("GRID.text", names(g))]]$label <- expr
  grb
}

l <- lm(mpg ~ log(disp), mtcars[mtcars$am == 1 & mtcars$gear == 5, ])

tt <- rename_panel_expression(ggplotGrob(p), 6, 
  bquote(italic(y)~`=`~.(round(l$coefficients[1], 3)) - .(round(abs(l$coefficients[2]), 3))*~italic(x)~~~italic(R)^2~`=`~.(round(summary(l)$r.squared, 3))))

grid::grid.newpage()
grid::grid.draw(tt)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多