简体   繁体   English

Python-创建直方图

[英]Python - creating a histogram

I'm using data of the form: [num1,num2,..., numk] (an array of integers). 我正在使用以下形式的数据: [num1,num2,..., numk] (整数数组)。

I would like to plot a histogram of a particular form, which I will use an example to describe. 我想绘制一个特定形式的直方图,我将用一个例子来描述它。

Suppose data = [0,5,7,2,3] . 假设data = [0,5,7,2,3] I want a histogram with: 我想要一个直方图:

  • Bins of width 1. 宽度为1。
  • x-axis ticks at 0,1,2,...,4 (one for each element of the array, eg if the array had 10 elements the ticks would run from 0 to 9) x轴刻度为0,1,2,...,4(数组的每个元素一个),例如,如果数组有10个元素,则刻度从0到9
  • For the bin between tick i and i+1, we have frequency (height) equal to data[i] + data[i+1] , eg between 1 and 2 we have a rectangle of height 12. 对于第i个时钟点和第i + 1个时钟点之间的bin,我们具有等于data[i] + data[i+1]频率(高度),例如在1和2之间,我们有一个高度为12的矩形。

How do I create such a histogram using matplotlib? 如何使用matplotlib创建此类直方图? Or numpy, if you prefer. 或numpy,如果您愿意。

histogram usage is eg here: 直方图的用法例如在这里:

http://matplotlib.org/examples/api/histogram_demo.html http://matplotlib.org/examples/api/histogram_demo.html

http://matplotlib.org/examples/pylab_examples/histogram_demo_extended.html http://matplotlib.org/examples/pylab_examples/histogram_demo_extended.html

I'd create this special data structure you want beforehand, then feed it into the histogram: 我会事先创建这个特殊的数据结构,然后将其输入直方图:

map(int.__add__, data[1:], data[0:-1])
> [5, 12, 9, 5]

If you already have numpy imported, you can also do 如果您已经导入了numpy,也可以执行

a=numpy.array(data[0:-1])
b=numpy.array(data[1:])
a+b
> array([ 5, 12,  9,  5])

I think this is what you are looking for: 我认为这是您要寻找的:

data = np.array([0,5,7,2,3])
datax = np.arange(np.size(data))
fig = plt.figure(1, figsize=(7,7))
ax  = fig.add_subplot(111)
ax.plot(datax[:-1], data[:-1]+data[1:], color='k')
ax.xaxis.set_ticks(datax)
ax.set_ylim(0,13)
ax.set_xlim(0,3)
plt.show()

which produces the following figure: 产生下图: 图是先前代码的结果

However it is not an histogram as you refer in your question. 但是,它不是您在问题中所指的直方图。 I actually do not understand why you are talking about a "histogram". 我实际上不明白您为什么要谈论“直方图”。

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

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