【问题标题】:Creating Histogram with Binning Averages使用分箱平均值创建直方图
【发布时间】:2014-08-09 23:52:06
【问题描述】:

我正在使用移动平均线和分箱制作两个直方图。通过使用 excel,我得到了 18k 数据点的移动平均值,其中大多数是 0 值。

这就是我希望通过 R 完成的工作

"Moving Average"

我想使用 R 来制作一个脚本,该脚本将生成一个设备收到多少“计数”的直方图。我试过了:

hist(y, 20)  
hist (y, ) 
plot (y, x) 

现在,经过三天的学习,这就是我得到的:

y <- AltWithAllCounts$Cts.p.ms
x <- AltWithAllCounts$Alt 
barwidth <- 100 
#how many bins
block <- rep(seq(1,length(x)/barwidth),each=barwidth)
#makes bins
a <- aggregate(y,by=list(block),sum) 
#creates sum of bins
altmean <- aggregate(x,by=list(block),mean)
#finds mean altitude of each bin
avgCount <- a$x/barwidth
#averages out each bin
plot(altmean$x,avgCount,xlab="Altitude",ylab="Counts") 
# creates scatterplot of mean bins
 avgBinCnt <- data.frame(altmean$x,a$x)
write.csv(avgBinCnt,file="avgBinCnt.csv",)

这个想法是我想要 20 个值的平均总和并随着时间的推移绘制它,即 x

x       y
851304  0
851404  0
851503  0
851603  1
851703  0
851804  0
851904  0
852107  0
852203  0
852303  0
922503  0
922603  2
922703  0
922804  0
922904  0
923107  0
923203  0
923303  0
923404  0
923504  0
923604  0
923703  0
923803  0
923904  0
924108  0
924205  1
1441603 0
1441703 0
1441804 0
1441904 0
1442107 1
1442203 1
1442304 0
1442404 4
1442504 0
1442605 1
1442703 6
1442803 8
1442904 0 

【问题讨论】:

    标签: r graphics average binning


    【解决方案1】:

    直方图显示频率,而不是间隔中的出现次数。要获得后者,可以执行以下操作:

    # First create some test data
    t <- seq(1,20000)
    p <- 2000
    s <- (sin(t*pi/p)+1)/2
    d <- ifelse(runif(length(s))<s,1,0)
    # Each element of d now contains a 1 or a 0, with a probability that varies
    # according to the sign function
    # Choose how many elements to count over
    barwidth <- 100
    # Create a vector of block numbers, with each numbered block having a length of 
    # barwidth
    block <- rep(seq(1,length(s)/barwidth),each=barwidth)
    # Now we aggregate with the sum to find the number of 1s in each block
    a <- aggregate(d,by=list(block),sum)
    # And plot it to show that we have the expected result
    barplot(a$x)
    

    ... 给出:

    对于频率散点图而不是计数条形图,这给出了所需的输出:

    midpoint <- aggregate(t,by=list(block),mean)
    plot(midpoint$x,a$x,xlab="",ylab="frequency")
    

    或者可以找到并绘制一个对称的移动平均值:

    filt <- rep(1/barwidth,barwidth)
    y_sym <- filter(d, filt, sides=2)
    plot(t,y_sym,xlab="",ylab="frequency")
    

    【讨论】:

    • 感谢您的快速回复。我更改了我的数据以反映我确实有大于 1 的值。
    • 我展示的方法同样适用于每个周期的计数超过一个的情况,以及每个周期的计数不超过一个的情况。虽然我绘制了计数的总和而不是平均计数,但我可以通过除法得到平均计数,例如avgCount &lt;- a$x/barwidth
    • 我更新了我的帖子并添加了一个指向我想要获得的散点图的链接。
    • 我仍在打印 sin() 函数。我希望了解如何在散点图中为分箱平均值和移动平均值编写代码,就像我在上面的超链接“移动平均值”中发布的链接一样。
    • 如果你在上面的代码中用你的向量y替换我的向量d,用你的向量x替换我的向量x,并使用对称移动平均代码,你会得到一个图表与您发布的完全一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    相关资源
    最近更新 更多