user27241
user27241

Reputation: 201

Plot multiple group histogram with overlaid line ggplot

I'm trying to plot a multiple group histogram with overlaid line, but I cannot get the right scaling for the histogram. For example:

  ggplot() + geom_histogram(data=df8,aes(x=log(Y),y=..density..),binwidth=0.15,colour='black') + 
geom_line(data = as.data.frame(pdf8), aes(y=pdf8$f,x=pdf8$x), col = "black",size=1)+theme_bw()

produces the right scale. But when I try to perform fill according to groups, each group is scaled separately.

ggplot() + geom_histogram(data=df8,aes(x=log(Y),fill=vec8,y=..density..),binwidth=0.15,colour='black') + 
  geom_line(data = as.data.frame(pdf8), aes(y=pdf8$f,x=pdf8$x), col = "black",size=1)+theme_bw()

Picture

How would I scale it so that a black line is overlaid over the histogram and on the y axis is density?

Upvotes: 1

Views: 3762

Answers (1)

JasonAizkalns
JasonAizkalns

Reputation: 20463

It is going to be difficult for others to help you without a reproducible example, but perhaps something like this is what you're after:

library(ggplot2)

ggplot(data = mtcars, aes(x = mpg, fill = factor(cyl))) +
  geom_histogram(aes(y = ..density..)) +
  geom_line(stat = "density")

R plot

If you would rather the density line pertain to the entire dataset, you need to move the fill aesthetic into the geom_histogram function:

ggplot(data = mtcars, aes(x = mpg)) +
  geom_histogram(aes(y = ..density.., fill = factor(cyl))) +
  geom_line(data = mtcars, stat = "density")

R plot 2

Upvotes: 2

Related Questions