Position text on a chart with a reverse axis in ggplot2

I am trying to display some statistics about the spread using geom_text(), but the text disappears when I cancel the x axis.

x = rnorm(20, mean = 10)
y = rnorm(20, mean =30)
R2 = cor(x, y)^2
R2 = signif(R2, 2)
df = data.frame(x, y)

#  It works on a normal axis.

library(ggplot2)
ggplot(df, aes(x = x, y = y)) + geom_point(shape = 1) +
  geom_text(label=paste("italic(R^2)==",R2), x = 10, y = 30, parse = T) +
  scale_x_continuous(limits = c(6, 14)) 

#  But the text disappears when I reverse the x-axis:

ggplot(df, aes(x = x, y = y)) + geom_point(shape = 1) +
  geom_text(label=paste("italic(R^2)==",R2), x = 10, y = 30, parse = T) +
  scale_x_continuous(limits = c(14, 6), trans="reverse") 

Thanks for any suggestions.

+4
source share
1 answer

The following will also write text only once and display the values, as in the first example that you specified:

labels <- data.frame(xval = 10, yval = 30, labeltext = paste("italic(R^2)==",R2))

ggplot(df, aes(x = x, y = y)) + 
  geom_point(shape = 1) +
  geom_text(data = labels, aes(x = xval, y = yval, label=labeltext), parse = T) +
  scale_x_continuous(limits = c(14, 6), trans="reverse") 
+1
source

Source: https://habr.com/ru/post/1545044/


All Articles