Create a histogram for weighted values

梦想的初衷 提交于 2019-11-27 06:38:39

问题


If I have a vector (e.g., v<-runif(1000)), I can plot its histogram (which will look, more or less, as a horizontal line because v is a sample from the uniform distribution).

However, suppose I have a vector and its associated weights (e.g., w<-seq(1,1000) in addition to v<-sort(runif(1000))). E.g., this is the result of table() on a much larger data set.

How do I plot the new histogram? (it should look more of less like the y=x line in this example).

I guess I could reverse the effects of table by using rep (hist(rep(v,w))) but this "solution" seems ugly and resource-heavy (creates an intermediate vector of size sum(w)), and it only supports integer weights.


回答1:


Package plotrix has a function weighted.hist which does what you want:

w<-seq(1,1000)
v<-sort(runif(1000))
weighted.hist(v, w)




回答2:


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

foo <- data.frame(v, w)

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




回答3:


An alternative from the weights package is wtd.hist()

w<-seq(1,1000) v<-sort(runif(1000)) wtd.hist(x=v,weight=w)



来源:https://stackoverflow.com/questions/19841204/create-a-histogram-for-weighted-values

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