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.

2
  • Possible duplicate of How to get data labels for a histogram in ggplot2? Commented Oct 18, 2015 at 14:05
  • @ scoa: I can't see how the question you referred to is solving this one. Please suggest an explicit solution. Commented Oct 18, 2015 at 14:19

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

@ vano: I am trying to pass the value of my.mean to be printed on the plot instead of some text
gplot <- gplot + geom_text(aes(15, 5, label=paste("Mean: ", my.mean)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.