Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot annotate with greek symbol and (1) apostrophe or (2) in between text

unable to add greek letters in ggplot annotate, when either: it is sandwiched in between other text, or the text in question contains an apostrophe.

For example, the following works fine:

df <- data.frame(x =  rnorm(10), y = rnorm(10))
temp<-paste("rho == 0.34")
ggplot(df, aes(x = x, y = y)) + geom_point() +
    annotate("text", x = mean(df$x), y = mean(df$y), parse=T,label = temp)

However, ggplot explodes when I do:

df <- data.frame(x =  rnorm(10), y = rnorm(10))
temp<-paste("Spearman's rho == 0.34")
ggplot(df, aes(x = x, y = y)) + geom_point() +
    annotate("text", x = mean(df$x), y = mean(df$y), parse=T,label = temp)

ggplot is frustratingly sensitive to these special characters. Other posts do not appear to address this issue (apologies if not). Thanks in advance.

like image 995
treetopdewdrop Avatar asked Dec 04 '14 20:12

treetopdewdrop


2 Answers

I've felt your frustration. The trick, in addition to using an expression for the label as commented by @baptiste, is to pass your label as.character to ggplot.

df <- data.frame(x =  rnorm(10), y = rnorm(10))
temp <- expression("Spearman's"~rho == 0.34)
ggplot(df, aes(x = x, y = y)) + 
  geom_point() + 
  annotate("text", x = mean(df$x), y = mean(df$y), 
           parse = T, label = as.character(temp))

enter image description here

like image 147
Scott Avatar answered Oct 17 '22 18:10

Scott


In case anyone is attempting to adopt this for a dynamic scenario where the correlation variable is not known beforehand, you can also create an escaped version of the expression as a string using:

df <- data.frame(x =  rnorm(10), y = rnorm(10))

spearmans_rho <- cor(df$x, df$y, method='spearman')
plot_label <- sprintf("\"Spearman's\" ~ rho == %0.2f", spearmans_rho)

ggplot(df, aes(x = x, y = y)) + 
  geom_point() + 
  annotate("text", x = mean(df$x), y = mean(df$y), parse = T, label=plot_label)
like image 33
Keith Hughitt Avatar answered Oct 17 '22 17:10

Keith Hughitt