Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot two histograms on single chart with matplotlib

I created a histogram plot using data from a file and no problem. Now I wanted to superpose data from another file in the same histogram, so I do something like this

n,bins,patchs = ax.hist(mydata1,100) n,bins,patchs = ax.hist(mydata2,100) 

but the problem is that for each interval, only the bar with the highest value appears, and the other is hidden. I wonder how could I plot both histograms at the same time with different colors.

like image 595
Open the way Avatar asked Jul 29 '11 09:07

Open the way


People also ask

How do you plot multiple histograms on one plot in Python?

To make multiple overlapping histograms, we need to use Matplotlib pyplot's hist function multiple times. For example, to make a plot with two histograms, we need to use pyplot's hist() function two times. Here we adjust the transparency with alpha parameter and specify a label for each variable.

How do you plot two histograms together?

For creating the Histogram in Matplotlib we use hist() function which belongs to pyplot module. For plotting two histograms together, we have to use hist() function separately with two datasets by giving some settings.

How do you show multiple histograms on the same axes?

In order to create two histograms on the same plot, similar to the PLOTYY function, you need to create overlapping axes and then plot each histogram on one axis.


2 Answers

Here you have a working example:

import random import numpy from matplotlib import pyplot  x = [random.gauss(3,1) for _ in range(400)] y = [random.gauss(4,2) for _ in range(400)]  bins = numpy.linspace(-10, 10, 100)  pyplot.hist(x, bins, alpha=0.5, label='x') pyplot.hist(y, bins, alpha=0.5, label='y') pyplot.legend(loc='upper right') pyplot.show() 

enter image description here

like image 114
joaquin Avatar answered Sep 28 '22 01:09

joaquin


The accepted answers gives the code for a histogram with overlapping bars, but in case you want each bar to be side-by-side (as I did), try the variation below:

import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-deep')  x = np.random.normal(1, 2, 5000) y = np.random.normal(-1, 3, 2000) bins = np.linspace(-10, 10, 30)  plt.hist([x, y], bins, label=['x', 'y']) plt.legend(loc='upper right') plt.show() 

enter image description here

Reference: http://matplotlib.org/examples/statistics/histogram_demo_multihist.html

EDIT [2018/03/16]: Updated to allow plotting of arrays of different sizes, as suggested by @stochastic_zeitgeist

like image 28
Gustavo Bezerra Avatar answered Sep 28 '22 02:09

Gustavo Bezerra