R:具有自定义间隔的直方图,用于自定义x轴范围 [英] R: Histogram with custom breaks for custom x axis range
问题描述
我需要绘制一个数字向量.假设这些数字的范围是0到1000.我需要制作一个x轴从100到500的直方图,并且我想将bin的数量指定为10.我该怎么做?
I need to plot a vector of numbers. Let's say these numbers range from 0 to 1000. I need to make a histogram where the x axis goes from 100 to 500, and I want to specify the number of bins to be 10. How do I do this?
我知道如何使用xlim并单独中断,但是我不知道如何在自定义范围内制作给定数量的垃圾箱.
I know how to use xlim and break separately, but I don't know how to make a given number of bins inside the custom range.
推荐答案
实际上,这是一个非常好的问题!我一直无时无刻不在困扰着您,但最终您的问题使我无奈了:-)
This is a very good question actually! I was bothered by this all the time but finally your question has kicked me to finally solve it :-)
好吧,在这种情况下,我们不能简单地执行hist(x, xlim = c(100, 500), breaks = 9)
,因为breaks
是指x的整个范围,与xlim
不相关(换句话说,xlim
仅用于绘图,不用于用于计算直方图并设置实际间隔).这是hist
函数的明显缺陷,在文档中找不到简单的补救方法.
Well, in this case we cannot simply do hist(x, xlim = c(100, 500), breaks = 9)
, as the breaks
refer to the whole range of x, not related to xlim
(in other words, xlim
is used only for plotting, not for computing the histogram and setting the actual breaks). This is a clear flaw of the hist
function and there is no simple remedy found in the documentation.
我认为最简单的方法是将之前的值"xlim"添加到hist
函数中:
I think the easiest way out is to "xlim" the values before they go to the hist
function:
x <- runif(1000, 0, 1000) # example data
hist(x[x > 100 & x < 500], breaks = 9)
breaks
应该是单元数减去一.
breaks
should be number of cells minus one.
有关更多信息,请参见 ?hist
For more info see ?hist
这篇关于R:具有自定义间隔的直方图,用于自定义x轴范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!