Histogram with weights in R

前提是你 提交于 2019-12-19 06:37:11

问题


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?


回答1:


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))



来源:https://stackoverflow.com/questions/30355938/histogram-with-weights-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!