8

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.

treetopdewdrop
  • 172
  • 5
  • 15

2 Answers2

7

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

Scott
  • 765
  • 4
  • 9
7

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)
Keith Hughitt
  • 4,860
  • 5
  • 49
  • 54
  • 1
    One may also want to retain trailing zeros, which `parse=TRUE` will normally discard. This can be done by also deparsing the numerical, i.e., `"\"Spearman's\" ~ rho == \"%0.2f\""`. – merv Oct 19 '21 at 16:40