ringgord
ringgord

Reputation: 65

Position text on a plot with reverse axis in ggplot2

I am trying to display some statistics on a scatter plot using geom_text(), but the text disappears when I reverse 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.

Upvotes: 4

Views: 1519

Answers (1)

tsurudak
tsurudak

Reputation: 602

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

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") 

Upvotes: 1

Related Questions