带权重的直方图R [英] Histogram with weights in R

查看:762
本文介绍了带权重的直方图R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要绘制密度的加权直方图而不是频率。我知道 freq = FALSE 可以在 hist()中使用,但是你不能指定权重。在 ggplot2 我可以这样做:

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

但是等价于 freq = FALSE

解决方案默认情况下, geom_histogram()将在y轴上使用频率而不是密度。但是,您可以通过将 y 审美设置为 .. density .. 来更改此设置:


$ b $

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

这将产生一个加权直方图,其密度为 v y轴。





您也可以在 weighted.hist() freq plotrix 包:

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

< img src =https://i.stack.imgur.com/otfGv.pngalt =plotrix>


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?

解决方案

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

这篇关于带权重的直方图R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆