Plot line graph from histogram data in matplotlib


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:


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


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?

Asked By: CNeo



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

Answered By: George

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

import numpy as np
import pylab as p

bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
Answered By: imsc

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

Answered By: Ger

Seaborn had what I needed:

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

sb.distplot(data, hist=False)
Answered By: PdevG

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

import seaborn

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

Answered By: PeJota
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.