通过R中的x值在直方图上缩放y轴的更好方法是什么?

时间:2022-01-05 14:56:48

Like the person who asked this question (How do I scale the y-axis on a histogram by the x values in R?), I am interested in plotting histograms scaled by a factor other than count.

就像问这个问题的人一样(我如何根据R中的x值在直方图上缩放y轴?),我感兴趣的是绘制由除计数以外的因子缩放的直方图。

I really like this solution suggested by one commenter:

我非常喜欢一位评论者建议的解决方案:

d<-rgamma(100,5,1.5)
z<-hist(d,plot=FALSE)
co<-z$counts # original counts of each bin
z$counts<-aggregate(d,list(cut(d,z$breaks)),sum)$x # sum up the value of data in each bin
plot(z)

However, this method does not give the appropriate answer if there are empty bins. For instance:

但是,如果有空箱,则此方法无法给出相应的答案。例如:

z2<-hist(d,plot=FALSE,breaks=100)
z2$counts<-aggregate(d,list(cut(d,z2$breaks)),sum)$x
plot(z2)

gives a histogram of clearly the wrong shape. It appears to repeat the non-empty bins as many times as is necessary to fill out the necessary slots.

给出了一个明确错误形状的直方图。似乎需要多次重复非空箱以填充必要的插槽。

Is there a better way of doing the same thing?

有没有更好的方法做同样的事情?

1 个解决方案

#1


1  

I think you want to only replace the elements in z2$counts where there are non-zero values:

我想你只想替换z2 $ count中存在非零值的元素:

z2<-hist(d,plot=FALSE,breaks=100)
z2$counts[z2$counts >0] <-aggregate(d,list(cut(d,z2$breaks)),sum)$x
plot(z2, ylab="Totals")

#1


1  

I think you want to only replace the elements in z2$counts where there are non-zero values:

我想你只想替换z2 $ count中存在非零值的元素:

z2<-hist(d,plot=FALSE,breaks=100)
z2$counts[z2$counts >0] <-aggregate(d,list(cut(d,z2$breaks)),sum)$x
plot(z2, ylab="Totals")