Search code examples
rggplot2annotateitalic

How to italicise part of correlation coefficient annotation in ggplot2


I cannot figure out how the make the letter "R" in the annotate() function below italicised on my plot. I've tried adding in expression() before paste(), and using italic(), but that then pastes the section starting "round(cor..." as text, rather than the result of the calculation.

    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)

Thanks

EDIT - the suggested possible duplicate does not seem to work for me. I think this might be due to the calculation of the correlation being embedded inside the annotate()?


Solution

  • This type of formatting is tricky. You need to pay attention to the white spaces when the parse=TRUE is used. To format the text you need proceed in two steps of pasting. Let's create a simple reproducible example:

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

    I recommend you to store the text AND the correlation value R outside of the ggplot function for readability of the code:

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

    The trick is to paste the two variables with the sep="~" instead of the white space.

    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)