dan
dan

Reputation: 6314

Add a geom_text/annotate layer to a geom_point layer overlaid on a geom_histogram

I have data that I want to plot in a geom_histogram, and it has a few points that I want to overlay on the histogram with geom_point and then annotate them (either with geom_text or annotate).

Here's the histogram and points:

#data
library(ggplot2)
set.seed(10)
df <- data.frame(id = LETTERS, val = rnorm(length(LETTERS)))

#points I want to overlay
selected.ids <- sample(LETTERS, 3, replace = F)
cols <- rainbow(length(selected.ids))
selected.df <- data.frame(id=selected.ids, col=cols, stringsAsFactors = F)
selected.df$x <- df$val[which(df$id %in% selected.ids)]
selected.df <- selected.df[order(selected.df$x),]
selected.df$col <- factor(selected.df$col, levels=cols)

#building the histogram
g <- ggplot(df, aes(x = val)) + geom_histogram(bins = 10, colour = "black", alpha = 0, fill = "#FF6666")

#finding the x,y locations of the points:
g.data <- ggplot_build(g)$data[[1]]
g.breaks <- c(g.data$xmin, tail(g.data$xmax, n=1))
selected.df$y <- g.data$count[findInterval(selected.df$x, g.breaks)]

To overlay the points I use:

g + geom_point(data = selected.df, aes(x = x, y = y, colour = factor(col)), size = 2) + 
  theme(legend.position="none")

which gives: enter image description here

And now trying to add the text with geom_text:

g + geom_point(data = selected.df, aes(x = x, y = y, colour = factor(col)), size = 2) + 
  annotate("text",size=2,x=selected.df$x,y=selected.df$y,label=selected.df$id)+
  theme(legend.position="none")

Throws this error:

Error in unique.default(x, nmax = nmax) : 
  unique() applies only to vectors

And with annotate:

g + geom_point(data = selected.df, aes(x = x, y = y, colour = factor(col)), size = 2) + 
  annotate("text",size=2,x=selected.df$x,y=selected.df$y,label=selected.df$id)+
  theme(legend.position="none")

No text is added.

Any idea?

Upvotes: 0

Views: 617

Answers (1)

J Hart
J Hart

Reputation: 89

I think what you are trying to do is like this. The geom_text should just be the same as the geom_point for the selected data.

g + geom_point(data = selected.df, aes(x = x, y = y, colour = factor(col)), size = 2) + 
geom_text(data=selected.df, aes(x=x, y=y, label=id))+
theme(legend.position="none")

Upvotes: 1

Related Questions