GBen
GBen

Reputation: 25

Overlaying histogram with different y-scales

I'm struggling with the following issue:

I want to plot two histograms, but since the statistics of one of the two classes is much less than the other I need to add a second y-axis to allow a direct comparison of the values.

I report below the code I used at the moment and the result.

Thank you in advance!


ggplot(data,aes(x= x ,group=class,fill=class)) + geom_histogram(position="identity",
  alpha=0.5, bins = 20)+ theme_bw() 

Plot

Upvotes: 1

Views: 2102

Answers (2)

teunbrand
teunbrand

Reputation: 38053

Consider the following situation where you have 800 versus 200 observations:

library(ggplot2)

df <- data.frame(
  x = rnorm(1000, rep(c(1, 2), c(800, 200))),
  class = rep(c("A", "B"), c(800, 200))
)

ggplot(df, aes(x, fill = class)) +
  geom_histogram(bins = 20, position = "identity", alpha = 0.5,
  # Note that y = stat(count) is the default behaviour
                 mapping = aes(y = stat(count)))

enter image description here

You could scale the counts for each group to a maximum of 1 by using y = stat(ncount):

ggplot(df, aes(x, fill = class)) +
  geom_histogram(bins = 20, position = "identity", alpha = 0.5,
                 mapping = aes(y = stat(ncount)))

enter image description here

Alternatively, you can set y = stat(density) to have the total area integrate to 1.

ggplot(df, aes(x, fill = class)) +
  geom_histogram(bins = 20, position = "identity", alpha = 0.5,
                 mapping = aes(y = stat(density)))

enter image description here

Note that after ggplot 3.3.0 stat() probably will get replaced by after_stat().

Upvotes: 3

Aron Strandberg
Aron Strandberg

Reputation: 3090

How about comparing them side by side with facets?

ggplot(data,aes(x= x ,group=class,fill=class)) +
  geom_histogram(position="identity",
                 alpha=0.5,
                 bins = 20) +
  theme_bw() +
  facet_wrap(~class, scales = "free_y")

Upvotes: 0

Related Questions