The answer here seems like it should get me to where I want, but I'm having trouble debugging an error while trying to apply it.
Here's some code (which works fine) to draw two distributions together, and 'zoom in' to crop the tallest bar of one of the distributions.
data(iris)
#Round Sepal.Length for Binning
iris$Sepal.Length = round(iris$Sepal.Length)
#Drop versicolor rows so density plot comes out skewed like my data
iris <- iris[iris$Species!="versicolor",]
#Plot density plot, truncating 0.8 column at (setosa, 5)
p <-ggplot(iris, aes(x=Sepal.Length, y=..density.., fill=Species)) +
geom_histogram(binwidth=1, alpha=0.5, position = 'identity') +
coord_cartesian(ylim = c(0, 0.6))
p
So far so good. Except when I add the code below to annotate the true height of the cropped bar
p + geom_text(data=as.data.frame(ggplot_build(p)$data),
aes(x=5, y=0.5, label = paste0("Bar Height: ", max(density))))
I get the error
Error in eval(expr, envir, enclos) : object 'Species' not found
Here's the output of as.data.frame(ggplot_build(p)$data)$density
0.10 0.80 0.10 0.00 0.00 0.00 0.02 0.54 0.32 0.12