ggplot2 - Adding italicised r with correlation coefficient to a scatter plot chart in ggplot -


i'm trying use code below generate simple scatter plot correlation coefficient have italicised r placed on plot.

data(mtcars)  # load required libraries require(ggplot2)               # derive graphs require(ggthemes)              # apply ggplot themes chart require(scales)                # pretty breaks  # function generate correlation coefficient charts corr_eqn <- function(x,y, digits = 2) {   corr_coef <- round(cor(x, y), digits = digits)   corr_coef <- expression(paste(italic(r)," = ", corr_coef))   return(corr_coef) }  # provide scatter plot income , health deprivation ggplot(mtcars, aes(x = drat, y = wt)) +   geom_point(shape = 19, size = 2, aes(colour = as.factor(cyl))) +   geom_smooth(colour = "red", fill = "lightgreen", method = 'lm') +   ggtitle("example") +   xlab("drat") +   ylab("wt") +   scale_colour_tableau("tableau10") +   geom_text(x = 3, y = 3,             label = corr_eqn(mtcars$drat,                              mtcars$wt), parse = true) +   theme(legend.key = element_blank(),         legend.background = element_rect(colour = 'black'),         legend.position = "bottom",         legend.title = element_blank(),         plot.title = element_text(lineheight = .8, face = "bold", vjust = 1),         axis.text.x = element_text(size = 11, vjust = 0.5,                                    hjust = 1, colour = 'black'),         axis.text.y = element_text(size = 11, colour = 'black'),         axis.title = element_text(size = 10, face = 'bold'),         axis.line = element_line(colour = "black"),         plot.background = element_rect(colour = 'black', size = 1),         panel.background = element_blank()) 

the code stops ? mark in console. running code lines:

#   geom_text(x = 3, y = 3, #             label = corr_eqn(mtcars$drat, mtcars$wt), parse = true) + 

commented, generates following chart: scatter plot

i'm guessing function generate equation of format r = 0.7 not work, how can fix it?

as suspected, need tweak function. have used substitute seen in this answer, can use paste here.

corr_eqn <- function(x,y, digits = 2) {   corr_coef <- round(cor(x, y), digits = digits)   paste("italic(r) == ", corr_coef) } 

enter image description here

note if you'd added as.character original function returned things have parsed. however, result have been corr_coef string instead of actual correlation coefficient wanted.

i should add geom_text can result in poor resolution if don't put labels , coordinates new data.frame.

labels = data.frame(x = 3, y = 3, label = corr_eqn(mtcars$drat, mtcars$wt)) 

then use data argument , aes geom_text:

geom_text(data = labels, aes(x = x, y = y,                         label = label), parse = true) 

see annotate geom = "text" option avoids new data.frame.


Comments