【问题标题】:How to put plotmath labels in ggplot facets如何将绘图标签放在ggplot方面
【发布时间】:2021-12-06 18:13:08
【问题描述】:

我们经常需要 ggplot 方面的单个回归方程。最好的方法是在数据框中构建标签,然后手动添加它们。但是如果标签包含绘图,例如上标呢?

【问题讨论】:

    标签: r ggplot2 regression plotmath


    【解决方案1】:

    这是一种方法。 plotmath 转换为字符串,然后由 ggplot 解析。 test_eqn 函数取自另一个 Stackoverflow 帖子,我会在再次找到它时链接它。对此感到抱歉。

    library(ggplot2)
    library(dplyr)
    
    test_eqn <- function(y, x){
      m <- lm(log(y) ~ log(x)) # fit y = a * x ^ b in log space
      p <- exp(predict(m)) # model prediction of y
      eq <- substitute(expression(Y==a~X^~b),
                       list(
                         a = format(unname(exp(coef(m)[1])), digits = 3),
                         b = format(unname(coef(m)[2]), digits = 3)
                      ))
      list(eq = as.character(eq)[2], pred = p)
    }
    
    set.seed(123)
    x <-  runif(20)
    y <-  runif(20)
    test_eqn(x,y)$eq
    #> [1] "Y == \"0.57\" ~ X^~\"0.413\""
    
    data <- data.frame(x = x,
                       y = y,
                       f = sample(c("A","B"), 20, replace = TRUE)) %>%
      group_by(f) %>%
      mutate(
        label = test_eqn(y,x)$eq, # add label
        labelx = mean(x),
        labely = mean(y),
        pred = test_eqn(y,x)$pred # add prediction
      )
    
    # plot fits (use slice(1) to avoid multiple copies of labels)
    ggplot(data) +
      geom_point(aes(x = x, y = y)) +
      geom_line(aes(x = x, y = pred), colour = "red") +
      geom_text(data = slice(data, 1), aes(x = labelx, y = labely, label = label), parse = TRUE) +
      facet_wrap("f")
    

    reprex package 创建于 2021-10-20 (v2.0.1)

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      相关资源
      最近更新 更多