How to Create a Violin Plot in Matplotlib

Spread the love

In this post, you will learn How to Create a Violin Plot in Matplotlib.

plt.violinplot() –

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()

Now to create a Violin Plot in Matplotlib, we use the plt.violinplot().

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.violinplot(df['Runs'])
plt.ylabel("Runs", fontsize=16)
plt.title("Violin Plot", fontsize=18)
plt.show()

Show Means and Median –

If you want, you can also show the means and the medians of the data in your violin plot using the showmean and showmedian parameters respectively.

plt.figure(figsize=(10, 8))
plt.violinplot(df['Runs'], showmeans=True, showmedians=True)
plt.ylabel("Runs", fontsize=16)
plt.title("Violin Plot", fontsize=18)
plt.show()

Create Horizontal Violin Plot –

To create a horizontal Violin Plot set the vert=False

plt.figure(figsize=(10, 8))
plt.violinplot(df['Runs'], vert=False, showmeans=True, showmedians=True)
plt.xlabel("Runs", fontsize=16)
plt.title("Violin Plot", fontsize=18)
plt.show()

Create Multiple Violin Plots –

# separate different groups of data
indian = df[df['Nationality']=='Indian']
overseas = df[df['Nationality']=='Overseas']

# for setting x tick labels
x_pos = [1, 2]
x_labels = ['Indian','Overseas']

# plot the figure
plt.figure(figsize=(10, 8))
plt.violinplot([indian['Runs'], overseas['Runs']], showmeans=True, showmedians=True)
plt.xticks(x_pos, x_labels)
plt.ylabel("Runs", fontsize=16)
plt.title("Violin Plot", fontsize=18)
plt.legend(['Indian','Overseas'])
plt.show()

Create Multiple Violin Plot In different Figures –

To create multiple violin plot in different figures instead of one, we can use the subplots in matplotlib. For more information – Subplots in Matplotlib.

# separate different groups of data
indian = df[df['Nationality']=='Indian']
overseas = df[df['Nationality']=='Overseas']

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,figsize=(10, 8))
ax1.violinplot(indian['Runs'], showmeans=True, showmedians=True)
ax1.set_title("Indian")
ax1.set_ylabel("Runs")
ax2.violinplot(overseas['Runs'], showmeans=True, showmedians=True)
ax2.set_title("Overseas")
plt.ylabel("Runs")
plt.show()

Rating: 1 out of 5.

Leave a Reply