14

I need to plot a weighted histogram of density rather than frequency. I know that freq = FALSE is available in hist() but you can't specify weights. In ggplot2 I can do this:

library(ggplot2)
w <- seq(1,1000)
w <-w/sum(w)
v <- sort(runif(1000))

foo <- data.frame(v, w)

ggplot(foo, aes(v, weight = w)) + geom_histogram()

But where is the equivalent of freq = FALSE?

Alex A.
  • 5,466
  • 4
  • 26
  • 56
heinheo
  • 557
  • 1
  • 4
  • 15
  • @ALexA. ho would I then set fre=F and not to null which is the default in hist() – heinheo May 20 '15 at 17:10
  • Possible duplicate of [Create a histogram for weighted values](https://stackoverflow.com/questions/19841204/create-a-histogram-for-weighted-values) – Arthur Yip Jun 21 '17 at 14:16

1 Answers1

14

By default, geom_histogram() will use frequency rather than density on the y-axis. However, you can change this by setting your y aesthetic to ..density.. like so:

ggplot(foo, aes(x = v, y = ..density.., weight = w)) + geom_histogram()

This will produce a weighted histogram of v with density on the y-axis.

weighted_density_histogram

You can also do this with the freq argument in weighted.hist() from the plotrix package:

library(plotrix)
with(foo, weighted.hist(v, w, freq = FALSE))

plotrix

Alex A.
  • 5,466
  • 4
  • 26
  • 56