5

I can add text to a ggplot using geom_text just fine (example using the cars database):

ggplot(cars, aes(speed, dist), color='blue') + 
geom_point(size=0.8) + 
geom_text(y=25, x=5, aes(label=paste("sigma == 1"), size=1.5), 
    hjust=0, parse=TRUE, color='blue')

But when I change the y scale to logarithmic, I can not get the text to appear on the graph:

ggplot(cars, aes(speed, dist), color='blue') + 
geom_point(size=0.8) + 
geom_text(y=25, x=5, aes(label=paste("sigma == 1"), size=1.5), 
    hjust=0, parse=TRUE, color='blue') + 
scale_y_log10()

I've tried varying the text size and position but can't seem to get it.

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Joseph Kreke
  • 667
  • 1
  • 7
  • 18

3 Answers3

7

This works for me:

require(ggplot2)
g <- ggplot(cars, aes(speed, dist), color='blue')
g <- g + geom_point(size=0.8)
g <- g + geom_text(aes(y=25, x=5, label=paste("sigma == 1"), size=1.5), hjust=0, parse=TRUE, color='blue')
g <- g + scale_y_log10()
g
CMichael
  • 1,856
  • 16
  • 20
  • Interesting and odd. That works for me. And now, when I reissue the commands as I did above, that too is working. Very strange. Thank you for your help. – Joseph Kreke Jan 09 '15 at 16:08
  • 1
    Well then it was just the y=25 and x=5 being outside the aes which gave ggplot a hickup... – CMichael Jan 09 '15 at 18:55
3

This works better:

ggplot(cars, aes(speed, dist), color='blue') + 
    geom_point(size=0.8) + 
    geom_text(y=2, x=5, aes(label=paste("sigma == 1"), size=1.5), 
        hjust=0, parse=TRUE, color='blue') + 
    scale_y_log10()

enter image description here

Normal to log scale: 100 -> 2; 1000 -> 3; 0.1 -> -1; 0.01 -> -2

1

The issue in the original code is that the x and y values are not wrapped up by aes(), so the axis transformation is not applied to them. To fix, just move the aes() to include all the aesthetics.

ggplot(cars, aes(speed, dist), color='blue') + 
  geom_point(size=0.8) + 
  geom_text(aes(y=25, x=5, label=paste("sigma == 1"), size=1.5), 
            hjust=0, parse=TRUE, color='blue') + 
  scale_y_log10()
Bruce M
  • 56
  • 3