geom_text() label statistics printing on top of each other in each facet of plot

1.5k views Asked by At

I have a faceted plot of probability distributions (histogram of y=..density.. with binwidth=1) as produced below.

library(ggplot2)
library(sqldf)
data(iris)

#Create Binned(Factor) Versions of Continuous Variables
iris$Sepal.Length = round(iris$Sepal.Length)
iris$Sepal.Width <- cut(iris$Sepal.Width, breaks = 4)

#Plot Probability Distributions of Sepal.Lengths, Separate Plots for Each Width-bin. 

p <-ggplot(iris, aes(x=Sepal.Length, y=..density..)) +
  geom_histogram(binwidth=1, alpha=0.5, position = 'identity', aes(fill=Species)) +
  facet_wrap(~Sepal.Width) 

p

enter image description here

I would like to add a geom_text() or geom_label() for a summary stat to each facet (e.g. max(density)).

Based on the answer here I tried this code, but got the plot below with each label printed on top of each other in each facet.

#Create DataFrame for Labels out of ggplot_build() data
ggbuild <- as.data.frame(ggplot_build(p)$data)
label.data = sqldf('select PANEL, max(density) as max_density from ggbuild group by PANEL ')

#Print Faceted Plot with Simple Summary Stat in Each Facet
p + geom_text(data=label.data, aes(x=.5, y=.8, label=paste0('Max Height: ', round(max_density,2))))

enter image description here

Based on this answer that "Sometimes it's easier to obtain summaries outside the call to ggplot," I tried the code below:

p + geom_text(aes(x=0, y=.8, label=label.data$max_density)) 

But that got me the following error:

Error: Aesthetics must be either length 1 or the same as the data (100): x, y, label

0

There are 0 answers