0

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

enter image description here

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
Community
  • 1
  • 1
Max Power
  • 8,265
  • 13
  • 50
  • 91
  • Seems to be similar to [this](http://stackoverflow.com/questions/12629647/adding-geom-path-and-geom-text-to-the-same-ggplot-generates-error-in-r) – Haboryme Dec 08 '16 at 17:49

1 Answers1

2

The problem is that you defined the aesthetic fill to be Species globally in the ggplot() statement. When you add the text geom, ggplot is looking for "Species" to determine the fill color, which doesn't exist in the second data frame.

You can solve this in two ways: either move the fill=Species from the ggplot statement to the geom_histogram statement:

p <-ggplot(iris, aes(x=Sepal.Length, y=..density..)) +
geom_histogram(binwidth=1, alpha=0.5, position = 'identity', aes(fill=Species)) +
coord_cartesian(ylim = c(0, 0.6))

or overwrite the fill aesthetic in the geom_text call:

p + geom_text(data=as.data.frame(ggplot_build(p)$data), 
          aes(x=5, y=0.5, fill='black', label = paste0("Bar Height: ", max(density))))

enter image description here

Edit: The picture above was produced using the second option. As you can see, ggplot added "black" as a third species in the legend. To avoid this, use the first option.

Community
  • 1
  • 1
hdkrgr
  • 1,666
  • 1
  • 12
  • 22