Reputation: 779
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.
Upvotes: 4
Views: 11268
Reputation: 3765
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)
Upvotes: 3
Reputation: 1054
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.
Upvotes: 2