如何在ggplot2中斜体化相关系数注释的一部分

时间:2018-10-05 08:25:22

标签: r ggplot2 annotate italic

我无法弄清楚下面的annotate()函数中的字母“ R”是如何以斜体显示的。我试过在expression()之前添加paste(),并使用italic(),但是然后将以“ round(cor ...”)开头的部分粘贴为文本,而不是计算。

    ggplot(subset(crossnat, !is.na(homicide) & !is.na(gdppercapita)),
  aes(x = gdppercapita, y = homicide)) +
  geom_point(alpha = 0.4) +
  ggtitle("Figure 3: Relationship between GDP per capita ($) and homicide rate") +
  labs(subtitle = "n = 177 (17 countries removed as either GDP per capita or homicide data unavailable",
       x = "GDP per capita ($)",
       y = "Number of homicides in 2013 (per 100k of population)") +
  scale_y_continuous(breaks = c(0,15,30,45,60,75,90)) +
  geom_smooth(method = "loess",
              formula = y ~ x,
              colour = "red",
              size = 0.5) +
  annotate(x = 50000, y = 75,
           label = paste("R = ", round(cor(crossnat$gdppercapita, crossnat$homicide, use = "complete.obs"),3)),
           geom = "text", size = 4)

谢谢

编辑-建议的可能重复项似乎对我不起作用。我认为这可能是由于相关性的计算嵌入了annotate()内?

1 个答案:

答案 0 :(得分:0)

这种格式很棘手。使用parse=TRUE时,请注意空白。要格式化文本,您需要分两个步骤进行粘贴。让我们创建一个简单的可复制示例:

ggData <- data.frame(x=rnorm(100), y=rnorm(100) )

我建议您将文本和相关值R存储在ggplot函数之外,以提高代码的可读性:

textPart1 <- "paste(italic(R), \" =\")"      # check the ?annotate example for \" =\"
corVal <- round(cor(ggData$x, ggData$y, use = "complete.obs"), 3)

诀窍是用paste而不是空格sep="~"来代替两个变量。

ggplot(ggData, aes(x = x, y = y) ) +
  geom_point(alpha = 0.4) + 
  annotate("text", x = 2, y = 1.5,
           label = paste(textPart1, corVal, sep="~"), size = 4 , parse=TRUE)