和而不是频率的直方图 - R.

时间:2015-05-06 16:39:41

标签: r histogram

我想绘制一个直方图,其中y轴代表一列的总和。 我找到了这个分类数据的例子: R histogram that sums rather than frequency。 但是,这不是我想要的,因为它不适用于连续数据,我必须在那里定义垃圾箱。

我们说我有x和y:

set.seed(1)
mydata <- data.frame(y = runif (100, min= 0, max = 1),
                 x = rpois(100, 15) * 10)

传统的直方图如下:

hist (mydata$x)

enter image description here

现在如何在y轴上得到y的累积和?

2 个答案:

答案 0 :(得分:3)

这是解决这个问题的一种方法,它利用了hist()函数来解决大部分繁重的问题,并且具有以下优点:y的累积和的条形图匹配x的直方图的区间和维度: / p>

set.seed(1)
mydata <- data.frame(y = runif (100, min= 0, max = 1), x = rpois(100, 15) * 10)
mx <- mydata$x
my <- mydata$y

h <- hist(mydata$x)

breaks <- data.frame(
    "beg"=h$breaks[-length(h$breaks)], 
    "end"=h$breaks[-1]
)

sums <- apply(breaks, MARGIN=1, FUN=function(x) { sum(my[ mx >= x[1] & mx < x[2] ]) })

h$counts <- sums
plot(h, ylab="Sum", main="Sum of y Within x Bins")

enter image description here

答案 1 :(得分:3)

总结所有评论,这就是我想要的。谢谢@Alex A。

set.seed(1)

mydata <- data.frame(y = runif (100, min= 0, max = 1), x = rpois(100, 15) * 10)

a <- aggregate(mydata$y, by=list(bin=cut(mydata$x, nclass.Sturges(mydata$x))), FUN=sum)
a$bin<- gsub (']','',as.character (a$bin))
a$bin<- gsub (',',' ',as.character (a$bin))

ab2=sapply(strsplit(as.character(a$bin), " "), "[", 2)
barplot(a$x, names.arg=ab2)

enter image description here

相关问题