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
?
A weighted histogram shows the weighted distribution of the data. If the histogram displays proportions (rather than raw counts), then the heights of the bars are the sum of the standardized weights of the observations within each bin.
You can also make histograms by using ggplot2 , “a plotting system for R, based on the grammar of graphics” that was created by Hadley Wickham. This post will focus on making a Histogram With ggplot2.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With