Skip to content
Prev 387267 / 398502 Next

overlaying frequency histograms or density plots in R

Hello,

First of all, I believe you want argument fill, not colour. In ggplot2 
colour is about the border and fill about the interior.

As for the question,

1. Create a basic plot with the common aesthetics.


library(ggplot2)

pp_ALL <- iris[c(1, 5)]
names(pp_ALL) <- c("VALUE", "EXP")

p <- ggplot(data = pp_ALL, mapping = aes(x = VALUE, fill = EXP))



2. geom_density should use alpha transparency, since the densities 
overlap. colour = NA removes the densities black border.


p + geom_density(alpha = 0.5, colour = NA)


3. y = ..density.. plots relative frequencies histograms, for the 
default absolute frequencies or counts, comment the mapping out.

position = position_dodge() allows for extra goodies, such as to change 
the space between bars, their width or to keep empty spaces when some 
factor levels are missing (preserve = "single").

For the test data, with 50 elements per factor level, use a much smaller 
number of bins.

Package scales has functions to display labels in percent format, there 
is no need to multiply by 100.


p + geom_histogram(
   mapping = aes(y = ..density..),
   position = position_dodge(),
   bins = 10)

p + geom_histogram(
   mapping = aes(y = ..density..),
   position = position_dodge(),
   bins = 10) +
   scale_y_continuous(labels = scales::label_percent())


Hope this helps,

Rui Barradas


?s 07:43 de 25/02/21, Bogdan Tanasa escreveu: