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()?
This type of formatting is tricky. You need to pay attention to the white spaces when the
parse=TRUEis used. To format the text you need proceed in two steps of pasting. Let's create a simple reproducible example:I recommend you to store the text AND the correlation value R outside of the
ggplotfunction for readability of the code:The trick is to
pastethe two variables with thesep="~"instead of the white space.