Josh
Josh

Reputation: 11

How to outline a histogram with a color and add a bell curve on ggplot2

I have been trying to add a bell curve to my histogram an outline it with a color so that it is more pleasing. enter image description here

I have added what my histogram looks like to give someone an idea on what I am working with, also here is my code thus far, thank you in advance.

ggplot(data = mammal.data.22.select2)+
  geom_histogram(aes(x=Time, fill=Species))+
  scale_fill_manual(values=c("paleturquoise4", "turquoise2"))+
  facet_wrap(~Species, nrow=1)+
  ylab("Observations")+
  xlab("Time of Day")+
  theme(strip.text.x = element_blank())

Upvotes: 1

Views: 467

Answers (1)

teunbrand
teunbrand

Reputation: 38003

Let's build a histogram with a build-in dataset that seems similar-ish to your data structure.

library(ggplot2)

binwidth <- 0.25

p <- ggplot(iris, aes(Petal.Length)) +
  geom_histogram(
    aes(fill = Species), 
    binwidth = binwidth, 
    alpha = 0.5
  ) +
  facet_wrap(~ Species)

You can use stat_bin() + geom_step() to give an outline to the histogram, without colouring the edge of every rectangle in the histogram. The only downside is that the first and last bins don't touch the x-axis.

p + stat_bin(
  geom = "step", direction = "mid",
  aes(colour = Species), binwidth = binwidth
)

To overlay a density function with a histogram, you could calculate the relevant parameters yourself and use stat_function() with fun = dnorm repeatedly. Alternatively, you can use ggh4x::stat_theodensity() to achieve a similar thing. Note that whether you use stat_function() or stat_theodensity(), you should scale the density back to the counts that your histogram uses (or scale histogram to density). In the example below, we do that by using after_stat(count * binwidth).

p + ggh4x::stat_theodensity(
  aes(colour = Species,
      y = after_stat(count * binwidth))
)

Created on 2022-04-15 by the reprex package (v2.0.1)

(disclaimer: I'm the author of ggh4x)

Upvotes: 4

Related Questions