Pandas Plotting – How to Create a Box Plot in Pandas

Spread the love

Create a Box Plot in Pandas –

Read the data for visualization.

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 pandas, we can use the DataFrame.boxplot() method

df.boxplot(column='Runs', figsize=(7, 6))

Multiple Box Plots –

You can also create multiple box plots to compare different groups.

df.boxplot(column='Runs', by='Team', figsize=(10,7))
plt.xticks(rotation=90)
plt.ylabel("Runs")
plt.title("")
plt.show()

If you want, you can further segment the data by adding one more dimension to the by parameter.

df.boxplot(column='Runs', by=['Team','Nationality'], figsize=(10,7))
plt.xticks(rotation=90)
plt.ylabel("Runs")
plt.title("")
plt.show()

Although it’s very crowded and unreadable as we have 9 groups here. But it can be useful if you have less numbers of groups.

You can also add more columns to the column parameter.

df.boxplot(column=['Runs','SR'], by='Nationality', figsize=(10,7))
plt.ylabel("Runs")
plt.show()

Rating: 1 out of 5.

Leave a Reply