带权重的直方图R [英] Histogram with weights in 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()$ c中使用
包: freq
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屋!