总和直方图而不是频率 - R
Histogram of sum instead of frequency - R
我想绘制一个直方图,其中 y 轴代表一列的总和。
我为分类数据找到了这个例子:
R histogram that sums rather than frequency。
但是,这不是我想要的,因为它不适用于连续数据,我必须在其中定义 bins。
假设我有 x 和 y:
set.seed(1)
mydata <- data.frame(y = runif (100, min= 0, max = 1),
x = rpois(100, 15) * 10)
传统直方图如下:
hist (mydata$x)
现在如何得到y轴上y的累加和?
这是解决此问题的一种方法,它利用 hist() 函数来完成大部分繁重的工作,其优点是 y 的累积和的条形图与 x 的直方图的 bin 和维度相匹配:
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")
总结所有评论,这就是我想要的。谢谢@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)
我想绘制一个直方图,其中 y 轴代表一列的总和。 我为分类数据找到了这个例子: R histogram that sums rather than frequency。 但是,这不是我想要的,因为它不适用于连续数据,我必须在其中定义 bins。
假设我有 x 和 y:
set.seed(1)
mydata <- data.frame(y = runif (100, min= 0, max = 1),
x = rpois(100, 15) * 10)
传统直方图如下:
hist (mydata$x)
现在如何得到y轴上y的累加和?
这是解决此问题的一种方法,它利用 hist() 函数来完成大部分繁重的工作,其优点是 y 的累积和的条形图与 x 的直方图的 bin 和维度相匹配:
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")
总结所有评论,这就是我想要的。谢谢@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)