I have a data frame with values and their associated weights. I want to make a histogram, such that each bar's height corresponds to the number of values in that bin and the bar's color corresponds to their total weight. How do I do that?
Example:
D <- data.frame(
x = c(-0.39, 0.12, 0.94, 1.67, 1.76, 2.44, 3.72, 4.28, 4.92, 5.53, 0.06,
0.48, 1.01, 1.68, 1.80, 3.25, 4.12, 4.60, 5.28, 6.22),
w = c(0.1810479, 0.2209460, 0.2974134, 0.3768152, 0.3871925, 0.4682943,
0.6220371, 0.6838944, 0.7473117, 0.7993555, 0.2159428, 0.2526883,
0.3046069, 0.3779629, 0.3918383, 0.5667588, 0.6667623, 0.7166747,
0.7790540, 0.8480375))
ggplot(D, aes(x)) +
geom_histogram(aes(y=..density..), binwidth=0.5, boundary=0.5)
Solution
Based on eipi10's answer, but using standard functions:
breaks <- seq(-0.5, 6.5, 0.5)
bins <- cut(D$x, breaks)
h <- data.frame(
x = head(breaks, -1) + 0.25,
count = sapply(split(D$x, bins), length),
weight = sapply(split(D$w, bins), sum))
h$density <- h$count / sum(h$count)
ggplot(h) + geom_bar(aes(x, density, fill=weight), stat='identity')