Laura
Laura

Reputation: 545

How to "fit" geom-histogram() and geom_density() in ggplot

I have this code:

ggplot(data = gapminder::gapminder, aes(x=lifeExp, group = continent,fill=continent)) + 
          geom_density(size=1.5,  alpha=0.5, color = 'transparent') +
          geom_histogram(aes(y=..density..), binwidth = 4, color="black", fill="lightblue", alpha=0.5)+
         
          geom_freqpoly(stat = 'density',bins = 30,color = 'yellow', size = .5)

What type of transformation I have to do to make the histogram and the density charts fit each other?

Upvotes: 1

Views: 38

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76641

First of all, copying and pasting from the warnings,

  • size was deprecated in ggplot2 3.4.0, use linewidth instead.
  • ..density.. was also deprecated in ggplot2 3.4.0, use after_stat(density) instead.

As for the plot, why set color = 'transparent' in the density aesthetic and then have a geom_freqpoly just to change that to 'yellow'? Plot the densities in yellow directly.

Now the plot, in two versions.
The first plot uses position_dodge() on the histogram's bars. I find it ugly and giving a confusing result.

library(ggplot2)

ggplot(data = gapminder::gapminder, 
       aes(x = lifeExp, group = continent, fill = continent)) + 
  geom_density(linewidth = 0.5,  alpha = 0.5, color = 'yellow') +
  geom_histogram(
    aes(y = after_stat(density)), 
    position = position_dodge(),
    binwidth = 4, 
    color = "black", fill = "lightblue", alpha = 0.5
  ) +
  theme_bw()

first plot

Created on 2025-03-02 with reprex v2.1.1

Better is to plot each continent separately. I chose the fill color of Asia above as the fill color of all densities.

library(ggplot2)

ggplot(data = gapminder::gapminder, aes(x = lifeExp)) + 
  geom_density(linewidth = 0.5,  alpha = 0.5, color = 'yellow', fill = "#75D5B4") +
  geom_histogram(
    aes(y = after_stat(density)), 
    binwidth = 4, 
    color = "black", fill = "lightblue", alpha = 0.5
  ) +
  facet_wrap(~ continent) +
  theme_bw()

second plot

Created on 2025-03-02 with reprex v2.1.1

Upvotes: 2

Related Questions