Brian Smith
Brian Smith

Reputation: 1353

Creating density plot and histogram in same plot using ggplot

I have below plot using R's ggplot library

library(ggplot2)
set.seed(1)

Dat = rbind(data.frame(var1 = 'x', var2 = rnorm(1000)), data.frame(var1 = 'y', var2 = rnorm(200, -10, 5)))

ggplot(Dat, aes(x = var2)) +
geom_density(aes(fill = var1), alpha = 0.4) 

However, instead of 2 density plots, I wanted to have histogram for var1 = 'y'. I also wanted to change the colour for both density plot and histogram.

Are there any way to achieve both using regular ggplot functions?

Any pointer will be highly appreciated.

Upvotes: 0

Views: 169

Answers (1)

Samet Sökel
Samet Sökel

Reputation: 2660

We can do it in this way;

library(ggplot2)
library(dplyr)

set.seed(1)

Dat <- rbind(data.frame(var1 = 'x', var2 = rnorm(1000)), data.frame(var1 = 'y', var2 = rnorm(200, -10, 5)))

Dat %>%
filter(var1!='y') %>% 
ggplot(aes(x=var2))+
geom_density(aes(fill=var1),alpha=.4)+
geom_histogram(data=Dat %>% filter(var1=='y'),aes(x=var2,y=..density..,fill=var1),alpha=.4)+
scale_fill_manual(values = c('x'='orange','y'='red'))

enter image description here

Upvotes: 2

Related Questions