1

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?

user27241
  • 201
  • 3
  • 10
  • 2
    Have you tried to change the position parameter? what position=dodge gives you? Also, are you sure that you are producing overlaid histograms? is more stacked ones to me. Try to play with the alpha parameter in order to see this. Also, http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Matias Andina Jun 14 '15 at 20:37

1 Answers1

2

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

Community
  • 1
  • 1
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116