简体   繁体   English

通过R?中的x值缩放直方图上的y轴的更好方法。

[英]Better method to scale the y-axis on a histogram by the x values in R?

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? 有没有更好的方法来做同样的事情?

I think you want to only replace the elements in z2$counts where there are non-zero values: 我认为您只想替换z2 $ counts中存在非零值的元素:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM