【问题标题】:How to adjust the position of regression equation on ggplot?如何调整回归方程在ggplot上的位置?
【发布时间】:2021-10-22 09:13:12
【问题描述】:

我想将回归线和 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

有什么建议吗?

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

谢谢,

【问题讨论】:

    标签: r ggplot2 regression equation lm


    【解决方案1】:

    我很确定使用geom 参数调整stat_poly_eq() 会得到你想要的。这样做会使方程居中,留下每个剪辑的左半部分,所以我们使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-26
      • 2019-11-01
      • 2020-11-10
      • 2020-08-27
      • 2020-10-16
      • 1970-01-01
      • 2023-04-05
      • 2013-03-16
      相关资源
      最近更新 更多