27

I have a numpy array of ints representing time periods, which I'm currently plotting in a histogram to get a nice distribution graph, using the following code:

ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r")

However I'm trying to modify this graph to represent the exact same data using a line instead of bars, so I can overlay more samples to the same plot and have them be clear (otherwise the bars overlap each other). What I've tried so far is to collate the data array into an array of tuples containing (time, count), and then plot it using

ax.plot(data[:,0],data[:,1],color="red",lw=2)

However that's not giving me anything close, as I can't accurately simulate the bins option of the histogram in my plot. Is there a better way to do this?

CNeo
  • 736
  • 1
  • 6
  • 10

5 Answers5

52

I am very late to the party - but maybe this will be useful to someone else. I think what you need to do is set the histtype parameter to 'step', i.e.

ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r", histtype = 'step')

See also http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html

Ger
  • 958
  • 1
  • 8
  • 11
39

You can save the output of hist and then plot it.

import numpy as np
import pylab as p

data=np.array(np.random.rand(1000))
y,binEdges=np.histogram(data,bins=100)
bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
p.plot(bincenters,y,'-')
p.show()
imsc
  • 7,492
  • 7
  • 47
  • 69
  • Any way to get this as bars, not as a line? I'm calculating histograms for different people, then averaging, so I've got average counts and want to construct a histogram-looking bar chart from those. – Amyunimus Sep 19 '12 at 04:35
  • Sure. Use `p.bar(bincenters,y,align='center')`. Check http://stackoverflow.com/a/12182440/302369 for details. – imsc Sep 19 '12 at 12:21
2

Seaborn had what I needed:

import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt

sb.distplot(data, hist=False)
plt.show()
PdevG
  • 3,427
  • 15
  • 30
  • Good answer, but distplot has been deprecated. An alternative is `seaborn.histplot(data, element = 'poly', fill= False)` – PJ_ Jul 21 '21 at 19:55
0

If using seaborn library, since distplot function has been deprecated:

import seaborn

seaborn.histplot(data, element = 'poly', fill= False)

PJ_
  • 473
  • 5
  • 9
0

Try ax.plot(zip(*data)[:][0],zip(*data)[:][1],color="red",lw=2)

George
  • 5,808
  • 15
  • 83
  • 160