How to Create a Histogram in Matplotlib

Spread the love

In this post, you will learn how to create a Histogram in Matplotlib.

plt.hist() –

Let’s read a dataset to work with.

import pandas as pd
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/batting.csv"
df = pd.read_csv(url)
df.head()

To create a histogram in matplotlib, we use the plt.hist() method.

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.hist(df['Runs'])
plt.xlabel('Runs')
plt.ylabel('Count')
plt.show()

To change the bins you can use the bins parameter. By default it is set to 10

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.hist(df['Runs'], bins=20)
plt.xlabel('Runs')
plt.ylabel('Count')
plt.show()

And to change the color of the histogram, use the color parameter.

plt.figure(figsize=(10, 8))
plt.hist(df['Runs'], bins=20, color='seagreen')
plt.xlabel('Runs')
plt.ylabel('Count')
plt.show()

By default the type of histogram to draw is bar but you can change that to other types like step, stepfilled and barstacked.

plt.figure(figsize=(10, 8))
plt.hist(df['Runs'], bins=20,histtype='step', color='seagreen')
plt.xlabel('Runs')
plt.ylabel('Count')
plt.show()

Create Multiple Histogram –

indian = df[df['Nationality']=='Indian']
overseas = df[df['Nationality']=='Overseas']

plt.figure(figsize=(10, 8))
plt.hist(indian['Runs'], label='Indian')
plt.hist(overseas['Runs'], label='Overseas')
plt.xlabel('Runs')
plt.ylabel('Count')
plt.show()

Create a Horizontal Histogram –

To create a horizontal histogram we can use orientation=’horizontal’ . By default it is vertical.

plt.figure(figsize=(10, 8))
plt.hist(df['Runs'], orientation='horizontal', color='seagreen')
plt.xlabel('Count')
plt.ylabel('Runs')
plt.savefig('histogram6')
plt.show()

Rating: 1 out of 5.

Leave a Reply