如何仅在ggplot的geom_label部分中操纵不同的单词和字母格式?

时间:2019-06-03 07:52:05

标签: r ggplot2

我一直试图将我的回归结果直接显示在情节中。即使我已经完成了主要任务,现在也需要美化图表。请看看我目前的情节。我想用R(下标2)代替R ^ 2,(斜体“ p”)值代替p值,并用实际的负号代替连字符(-)。

我认为可以在代码的geom_label()部分中进行某些更改以实现此结果。但是由于我的知识有限,我无法实现这一目标。

ggplotRegressionr <- function (fit, title_of_graph, n, m) {

  require(ggplot2)

  ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() + 
    geom_line() + 
    geom_label(aes(1990, m, hjust = 0, vjust = 0, 
                   label = paste("R^2 = ",signif(summary(fit)$adj.r.squared, 3),"\n",
                                 "Slope =",signif(fit$coef[[2]], 3),"\n",
                                 "p-value =",signif(summary(fit)$coef[2,4], 3)))) +
    stat_smooth(method = "lm", col = "red") + 
    xlab("Year") + ylab("Total Precipitation") +
    labs(title = title_of_graph) + 
    scale_y_continuous(limits = c(0, n)) +
    theme(plot.title = element_text(hjust = 0.5))

}

任何帮助将不胜感激。非常感谢你。

当前图形输出: Current graph output i have achieved is in the image

1 个答案:

答案 0 :(得分:2)

如果您是乳胶迷,则可以使用软件包latex2exp,尽管我遇到了一个问题,即我无法在值之间添加新行,所以我为每个值加上了一层背景白盒的图层,这有点麻烦,因为您必须为文本和白色矩形选择正确的坐标,但这确实起作用,这就是我的意思:

library(ggplot2)
library(latex2exp)

# Dummy values
r2 <- - 0.00888
sl <- - 0.00777
p <- 0.666

# text for the labels
# with gsub add space after the minus sign to get the right sign when latex is rendered 
txt1 <- paste0("$R^2 = ", gsub('-', '- ', r2), "$")
txt2 <- paste0("$Slope = ", gsub('-', '- ', sl), "$")
txt3 <- paste0("$\\mathit{p}-value = ", gsub('-', '- ', p), "$")

# plot
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_line() +
  geom_smooth(method = lm)  +
  annotate('rect', 
           xmin = 5, xmax = 6.1,
           ymin = 39, ymax = 45,
           size=0.5, 
           fill = 'white', color = 'black') +
  annotate('text', x=5.1, y=43.5, 
           hjust = 0, vjust = 0, 
           size=5,
           label=TeX(txt1)) + 
      #     label=TeX('$R^2 = - 1.5$'), parse = TRUE) + 
  annotate('text', x=5.1, y=41.5,
           hjust = 0, vjust = 0, 
           size=5,
           label=TeX(txt2)) + 
  annotate('text', x=5.1, y=39.5, 
           hjust = 0, vjust = 0, 
           size=5,
           label=TeX(txt3))

enter image description here