How to Create a Box Plot in Matplotlib

Spread the love

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

plt.boxplot() –

Reading a dataset for illustration.

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 Box Plot in Matplotlib, we use the plt.boxplot() method.

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.boxplot(df['Runs'])
plt.ylabel("Runs")
plt.title("Box Plot")
plt.show()

To create Notched Boxes, set notch to True.

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.boxplot(df['Runs'], notch=True)
plt.ylabel("Runs")
plt.title("Box Plot")
plt.show()

And to change the outliers symbols use the flierprops parameter

import matplotlib.pyplot as plt

green_diamond = dict(markerfacecolor='g', marker='D')
plt.figure(figsize=(10, 8))
plt.boxplot(df['Runs'], flierprops=green_diamond)
plt.ylabel("Runs")
plt.title("Changed Outlier Symbols")
plt.show()

And to hide outliers, set the showfliers=False


plt.figure(figsize=(10, 8))
plt.boxplot(df['Runs'], showfliers=False)
plt.ylabel("Runs")
plt.title("Hide Outliers")
plt.show()

Create Horizontal Box Plot –

To create a vertical box plot, set the vert=False

plt.figure(figsize=(10, 8))
plt.boxplot(df['Runs'], vert=False)
plt.xlabel("Runs")
plt.title("Horizontal Box Plot")
plt.show()

Multiple Box Plots –

To create multiple box plot, pass the data in a list to the boxplot method.

# get the data for different groups
indian = df[df['Nationality']=='Indian']
overseas = df[df['Nationality']=='Overseas']

# create the data and labels
data = [indian['Runs'], overseas['Runs']]
labels = ['Indian','Overseas']

# plot the figure
plt.figure(figsize=(10, 8))
plt.boxplot(data, labels=labels)
plt.title("Multiple Box Plot", fontsize=16)
plt.xlabel("Nationality", fontsize=14)
plt.ylabel("Runs", fontsize=14)
plt.savefig("box_mat6")
plt.show()

Rating: 1 out of 5.

Leave a Reply