【发布时间】: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 中做所有事情。
-
没有一个答案能解决您的问题