首页 > 解决方案 > 如何调整回归方程在ggplot上的位置?

问题描述

我想将回归线和 R^2 添加到我的 ggplot 中。我将回归线拟合到不同的类别,并且对于每个类别,我都会得到一个独特的方程。我想手动为每个类别设置方程的位置。即为每个组找到 y 的最大表达式并在 ymax + 1 处打印方程。

这是我的代码:

library(ggpmisc)
df <- data.frame(x = c(1:100))
df$y <- 20 * c(0, 1) + 3 * df$x + rnorm(100, sd = 40)
df$group <- factor(rep(c("A", "B"), 50))
df <- df %>% group_by(group) %>% mutate(ymax = max(y))
my.formula <- y ~ x
df %>%
   group_by(group) %>%
   do(tidy(lm(y ~ x, data = .))) 

p <- ggplot(data = df, aes(x = x, y = y, colour = group)) +
   geom_smooth(method = "lm", se=FALSE, formula = my.formula) +
   stat_poly_eq(formula = my.formula, 
             aes(x = x , y = ymax + 1, label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
              parse = TRUE) +         
   geom_point()
p

任何建议如何做到这一点?

还有什么办法我只能打印方程的斜率。(从情节中删除截距)?

谢谢,

标签: rggplot2regressionequationlm

解决方案


我很确定stat_poly_eq()使用geom参数调整设置会得到你想要的。这样做会使方程居中,留下每个剪辑的左半部分,所以我们用hjust = 0左调整方程。最后,根据您的具体数据,方程可能会相互重叠,因此我们使用position参数让 ggplot 尝试将它们分开。

这个调整后的电话应该让你开始,我希望:

p <- ggplot(data = df, aes(x = x, y = y, colour = group)) +
   geom_smooth(method = "lm", se=FALSE, formula = my.formula) +
   stat_poly_eq(
      formula = my.formula, 
      geom = "text",  # or 'label'
      hjust = 0,  # left-adjust equations
      position = position_dodge(),  # in case equations now overlap
      aes(x = x , y = ymax + 1, label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
      parse = TRUE) +         
   geom_point()
p

推荐阅读