FacundoGFlores
FacundoGFlores

Reputation: 8118

How to plot an ogive?

I'm wondering if there exists a way to plot a histogram and an ogive using matplotlib in Python.

I have the following for plotting a histogram

a = np.array(values)
plt.hist(a, 32, normed=0, facecolor='blue', alpha = 0.25)
plt.show()

But I don't know if matplotlib has got a good way to plot an ogive.

Here's what I'm doing:

a = np.array(values)
bins = np.arange(int(min), int(max) + 2)
histogram = np.histogram(a, bins = bins, normed = True)
v = []
s = 0.0
for e in histogram[0]:
    s = s + e
    v.append(s)
v[0] = histogram[0][0]
plt.plot(v)
plt.show()

Upvotes: 2

Views: 2863

Answers (2)

Joe Kington
Joe Kington

Reputation: 284750

By ogive do you just mean a cumulative histogram? If so, just pass cumulative=True to plt.hist.

For example:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.normal(0, 1, 1000)

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.hist(data)
ax2.hist(data, cumulative=True)
plt.show()

enter image description here

If you want it to be drawn as a line, just use numpy.histogram directly (that's what plt.hist is using). Alternately, you can use the values that plt.hist returns. counts and bins are what np.histogram would return; plt.hist just returns the plotted patches as well.

For example:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.normal(0, 1, 1000)

fig, ax = plt.subplots()
counts, bins, patches = plt.hist(data)

bin_centers = np.mean(zip(bins[:-1], bins[1:]), axis=1)
ax.plot(bin_centers, counts.cumsum(), 'ro-')

plt.show()

enter image description here

Upvotes: 5

Paul H
Paul H

Reputation: 68186

The question in its current form is pretty vague. Are the x and y scale similar or different? Assuming equal x-scale, it should be pretty simple. Note that since you haven't provided any data, I haven't tested the code below

import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

ax1.hist(values, 32, normed=0, facecolor='blue', alpha=0.25)
ax2.plot(x_ogive, y_ogive, marker='none', linestyle='-', color='black')

ax1.set_xlabel('X-data')
ax1.set_ylabel('Counts')
ax2.set_ylabel('Ogive Surface')

fig.savefig('OgiveAndHist.png')

Upvotes: 1

Related Questions