本文介绍了如何从频率表中绘制密度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出下面的频率表:
> print(dat)
V1 V2
1 1 11613
2 2 6517
3 3 2442
4 4 687
5 5 159
6 6 29
# V1 = Score
# V2 = Frequency
我们如何绘制密度,(即 y 轴范围从 0 到 1.0).
How can we plot the density, (i.e. y-axis range from 0 to 1.0).
目前我有以下频率图:
plot(0,main="table",type="n");
lines(dat,lty=1)
# I need to use lines() and plot() here,
# because need to make multiple lines in single plot
不确定如何处理密度.
推荐答案
假设每一行都是一个单独的块,那么每个块的密度将为 V2/sum(V2)
.
The density of each block would be V2 / sum(V2)
assuming that each row is a separate block.
为了您的数据
dat <- data.frame(V1 = 1:6, V2 = c(11613, 6517, 2442, 687, 159, 29))
我明白了:
> with(dat, V2 / sum(V2))
[1] 0.541474332 0.303865342 0.113862079 0.032032452 0.007413624 0.001352170
我们可以使用 R 的工具进行检查.首先展开你的紧凑频率表
Which we can check using R's tools. First expand your compact frequency table
dat2 <- unlist(apply(dat, 1, function(x) rep(x[1], x[2])))
然后使用hist()
来计算我们想要的值
Then use hist()
to compute the values we want
dens <- hist(dat2, breaks = c(0:6), plot = FALSE)
查看生成的对象:
> str(dens)
List of 7
$ breaks : int [1:7] 0 1 2 3 4 5 6
$ counts : int [1:6] 11613 6517 2442 687 159 29
$ intensities: num [1:6] 0.54147 0.30387 0.11386 0.03203 0.00741 ...
$ density : num [1:6] 0.54147 0.30387 0.11386 0.03203 0.00741 ...
$ mids : num [1:6] 0.5 1.5 2.5 3.5 4.5 5.5
$ xname : chr "dat2"
$ equidist : logi TRUE
- attr(*, "class")= chr "histogram"
注意 密度
组件是:
> dens$density
[1] 0.541474332 0.303865342 0.113862079 0.032032452 0.007413624 0.001352170
这与我从原始频率表表示中手工计算的结果一致.
Which concurs with my by-hand calculation from the original frequency table representation.
至于绘图,如果您只想绘制密度,请尝试:
As for the plotting, if you just want to draw densities instead then try:
dat <- transform(dat, density = V2 / sum(V2))
plot(density ~ V1, data = dat, type = "n")
lines(density ~ V1, data = dat, col = "red")
如果你想强制轴限制做:
If you want to force axis limits do:
plot(density ~ V1, data = dat, type = "n", ylim = c(0,1))
lines(density ~ V1, data = dat, col = "red")
这篇关于如何从频率表中绘制密度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!