Violin Plotting With Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create violin plots using Matplotlib library in Python. Violin plots are used to visualize the distribution of a dataset. These plots are similar to box plots, but instead of showing only the summary statistics, violin plots show the full distribution of the data.

We will use a sample dataset to create violin plots and modify various parameters to observe changes in the plot.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/SpecializedPlotsGroup(["`Specialized Plots`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/violin_plots("`Violin Plots`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills python/comments -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} matplotlib/figures_axes -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} matplotlib/violin_plots -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/booleans -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/for_loops -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/list_comprehensions -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/lists -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/tuples -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/importing_modules -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/standard_libraries -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/math_random -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/numerical_computing -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} python/data_visualization -.-> lab-49023{{"`Violin Plotting With Matplotlib`"}} end

Import necessary libraries

We will start by importing the necessary libraries to create the violin plots.

import matplotlib.pyplot as plt
import numpy as np

Create sample dataset

We will create a sample dataset using numpy library. We will create six datasets with different standard deviations.

## Fixing random state for reproducibility
np.random.seed(19680801)

## fake data
pos = [1, 2, 4, 5, 7, 8]
data = [np.random.normal(0, std, size=100) for std in pos]

Create custom violin plots

We will create custom violin plots by modifying various parameters. We will create 5 custom violin plots using different parameters.

fig, axs = plt.subplots(nrows=2, ncols=5, figsize=(10, 6))

## Custom violinplot 1
axs[0, 0].violinplot(data, pos, points=20, widths=0.3,
                     showmeans=True, showextrema=True, showmedians=True)
axs[0, 0].set_title('Custom violinplot 1', fontsize=fs)

## Custom violinplot 2
axs[0, 1].violinplot(data, pos, points=40, widths=0.5,
                     showmeans=True, showextrema=True, showmedians=True,
                     bw_method='silverman')
axs[0, 1].set_title('Custom violinplot 2', fontsize=fs)

## Custom violinplot 3
axs[0, 2].violinplot(data, pos, points=60, widths=0.7, showmeans=True,
                     showextrema=True, showmedians=True, bw_method=0.5)
axs[0, 2].set_title('Custom violinplot 3', fontsize=fs)

## Custom violinplot 4
axs[0, 3].violinplot(data, pos, points=60, widths=0.7, showmeans=True,
                     showextrema=True, showmedians=True, bw_method=0.5,
                     quantiles=[[0.1], [], [], [0.175, 0.954], [0.75], [0.25]])
axs[0, 3].set_title('Custom violinplot 4', fontsize=fs)

## Custom violinplot 5
axs[0, 4].violinplot(data[-1:], pos[-1:], points=60, widths=0.7,
                     showmeans=True, showextrema=True, showmedians=True,
                     quantiles=[0.05, 0.1, 0.8, 0.9], bw_method=0.5)
axs[0, 4].set_title('Custom violinplot 5', fontsize=fs)

Create more custom violin plots

We will create more custom violin plots using different parameters.

## Custom violinplot 6
axs[1, 0].violinplot(data, pos, points=80, vert=False, widths=0.7,
                     showmeans=True, showextrema=True, showmedians=True)
axs[1, 0].set_title('Custom violinplot 6', fontsize=fs)

## Custom violinplot 7
axs[1, 1].violinplot(data, pos, points=100, vert=False, widths=0.9,
                     showmeans=True, showextrema=True, showmedians=True,
                     bw_method='silverman')
axs[1, 1].set_title('Custom violinplot 7', fontsize=fs)

## Custom violinplot 8
axs[1, 2].violinplot(data, pos, points=200, vert=False, widths=1.1,
                     showmeans=True, showextrema=True, showmedians=True,
                     bw_method=0.5)
axs[1, 2].set_title('Custom violinplot 8', fontsize=fs)

## Custom violinplot 9
axs[1, 3].violinplot(data, pos, points=200, vert=False, widths=1.1,
                     showmeans=True, showextrema=True, showmedians=True,
                     quantiles=[[0.1], [], [], [0.175, 0.954], [0.75], [0.25]],
                     bw_method=0.5)
axs[1, 3].set_title('Custom violinplot 9', fontsize=fs)

## Custom violinplot 10
axs[1, 4].violinplot(data[-1:], pos[-1:], points=200, vert=False, widths=1.1,
                     showmeans=True, showextrema=True, showmedians=True,
                     quantiles=[0.05, 0.1, 0.8, 0.9], bw_method=0.5)
axs[1, 4].set_title('Custom violinplot 10', fontsize=fs)

Customize plot appearance

We will customize the appearance of the plot by removing y-axis labels and adding a title to the plot.

for ax in axs.flat:
    ax.set_yticklabels([])

fig.suptitle("Violin Plotting Examples")
fig.subplots_adjust(hspace=0.4)
plt.show()

Summary

In this lab, we learned how to create violin plots using Matplotlib library in Python. We created custom violin plots by modifying various parameters such as number of points, bandwidth of KDE, and quantiles. We also learned how to customize the appearance of the plot by removing y-axis labels and adding a title to the plot.

Other Python Tutorials you may like