4

Is it possible to annotate a ggplot figure with a "text" element indicating a feature of the data (variable)?

library(ggplot2)
library(datasets)    
my.mean <- mean(mtcars$mpg, na.rm=T)
my.mean <- as.name(my.mean)

gplot <- ggplot(mtcars, aes(mpg))+geom_histogram()
gplot <- gplot + geom_text(aes_string(label=my.mean, y=5), size=3)

This produces something on the plot that looks like a succession of numbers. Any ideas how to resolve this?

Edit: this question is different since I am not trying to annotate each histogram bin with a value. The objective is to add one single text element to the plot.

remi
  • 781
  • 2
  • 13
  • 22
  • Possible duplicate of [How to get data labels for a histogram in ggplot2?](http://stackoverflow.com/questions/24198896/how-to-get-data-labels-for-a-histogram-in-ggplot2) – scoa Oct 18 '15 at 14:05
  • @ scoa: I can't see how the question you referred to is solving this one. Please suggest an explicit solution. – remi Oct 18 '15 at 14:19

2 Answers2

3

If I understood you right, you want to add a text to your plot which is defined by another dataset, i.e. a dataset which was not given as argument to ggplot().

Solution: Pass this dataset directly to your geom_text function using data=... to use it.

library(ggplot2) library(datasets)
my.mean <- mean(mtcars$mpg, na.rm=T)

ggplot(mtcars, aes(mpg)) +
        geom_histogram() + 
        geom_text(data=data.frame(my.mean=my.mean), aes(y=5, x=my.mean, label=my.mean), size=3)
Matthias Munz
  • 3,583
  • 4
  • 30
  • 47
2

it should work like this:

gplot <- gplot + geom_text(aes(15, 5, label="some random text"))
gplot

with the numbers you can specify the location within your grid.

vanao veneri
  • 970
  • 2
  • 12
  • 31