s3b4s
s3b4s

Reputation: 93

How can I plot a filled histogram and its density with ggplot2?

I have this histogram created with ggplot2:

x = rnorm(100,0,150)
df <- data.frame(val=c(x))
ggplot(df, aes(val,..density.., fill = ..x..>100)) + 
  geom_histogram(binwidth=bw.SJ(df$val), colour="black") +
  scale_fill_hue(h=c(115,230))

I'd like to add the pdf to this histogram, but when the next line is added:

geom_density(colour="red", lwd=1) +

This returns the error:

Error in get(x, envir = this, inherits = inh)(this, ...) : 
  Aesthetics can not vary with a ribbon

Thanks in advance!

Upvotes: 2

Views: 1915

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81733

It should work if you specify fill = ..x..>100) inside geom_histogram and not for the whole plot. You can't vary the fill colour over a density.

ggplot(df, aes(val)) + 
  geom_histogram(aes(fill = ..x.. > 100), 
                 binwidth = bw.SJ(df$val), colour = "black") +
  scale_fill_hue(h = c(115, 230)) +
  geom_density(colour = "red", lwd = 1)

Upvotes: 4

wibeasley
wibeasley

Reputation: 5287

Does it work without any arguments in the density call? If so try

geom_density(colour="red", size=1) +

instead of

geom_density(colour="red", lwd=1) +

If that doesn't work, a reproducible example could help.

Upvotes: 0

Related Questions