Mel
Mel

Reputation: 175

Python - creating a histogram

I'm using data of the form: [num1,num2,..., numk] (an array of integers).

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]. I want a histogram with:

How do I create such a histogram using matplotlib? Or numpy, if you prefer.

Upvotes: 1

Views: 1642

Answers (2)

Alejandro
Alejandro

Reputation: 3412

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: Figure is the result of the previous code

However it is not an histogram as you refer in your question. I actually do not understand why you are talking about a "histogram".

Upvotes: 0

Christoph
Christoph

Reputation: 5612

histogram usage is e.g. here:

http://matplotlib.org/examples/api/histogram_demo.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

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

Upvotes: 1

Related Questions