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.
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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With