【问题标题】:Using R how do I add superscript in a title in ggplot2?使用 R 如何在 ggplot2 的标题中添加上标?
【发布时间】:2023-01-11 04:26:15
【问题描述】:

我查看了其他一些线程并尝试使用表达式和 bquote 但没有任何运气。我是 R 的初学者,希望对这个具体示例有所帮助。我在另一个网站上找到了以下代码,它对我有用,但我无法在 R2 上标中添加 2。

这是初始代码:

ggplotRegression <- function (fit) {

require(ggplot2)

ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() +
    stat_smooth(method = "lm") +
    labs(title = paste("R2 = ",signif(summary(fit)$r.squared, 5),
                     "Intercept =",signif(fit$coef[[1]],5 ),
                     " Slope =",signif(fit$coef[[2]], 5),
                     " P =",signif(summary(fit)$coef[2,4], 5)))
}

ggplotRegression(lm(TOA_NDVI ~ Field_NDVI, data = NDVI_type))

这是我尝试过的事情之一:

ggplotRegression <- function (fit) {

require(ggplot2)

ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() +
    stat_smooth(method = "lm") +
    labs(title = paste(expression("R^2 *="),signif(summary(fit)$r.squared, 5)),
                     "Intercept =",signif(fit$coef[[1]],5 ),
                     " Slope =",signif(fit$coef[[2]], 5),
                     " P =",signif(summary(fit)$coef[2,4], 5)))
}

ggplotRegression(lm(TOA_NDVI ~ Field_NDVI, data = NDVI_type)) 

非常感谢任何帮助,谢谢。

【问题讨论】:

    标签: r superscript


    【解决方案1】:

    您可以使用“bquote”。这是代码:

    ggplotRegression <- function (fit) {
      
      require(ggplot2)
      
      ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
        geom_point() +
        stat_smooth(method = "lm") +
        labs(title = bquote(R^2== .(signif(summary(fit)$r.squared, 5))~
                              "Intercept = "~ .(signif(fit$coef[[1]],5 )) ~
                              " Slope = "~ .(signif(fit$coef[[2]], 5)) ~
                              " P = "~ .(signif(summary(fit)$coef[2,4], 5)) ))
    }
    
    ggplotRegression(lm(speed ~ dist, data = cars))
    

    这是生成的图:

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      相关资源
      最近更新 更多