Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Violin Plots in Matplotlib

Learn how to create violin plots using Matplotlib. Understand data distribution, probability density, median, quartiles, bandwidth and violin plot customization.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand what a violin plot is.
  • Understand probability density and data distribution.
  • Create basic violin plots using Matplotlib.
  • Compare multiple datasets using violin plots.
  • Display means, medians and quartiles.
  • Customize violin plot colours and appearance.
  • Control violin width and bandwidth.
  • Create horizontal violin plots.
  • Understand the difference between box plots and violin plots.

2. Introduction to Violin Plots

A violin plot is a statistical chart used to visualize the distribution and density of numerical data. It combines information from a box plot and a probability density plot.

The width of a violin at a particular value represents the estimated density of observations around that value. Wider regions indicate a higher concentration of data, while narrower regions indicate a lower concentration.

Real-Life Example

Suppose a teacher wants to compare examination marks from three classes. A violin plot can show where most students scored, how widely marks are distributed and whether the data contains multiple concentration areas.

Violin Plot Wider area = Higher data density Narrower area = Lower data density Centre line = Median indicator Shape = Estimated distribution Data values

Conceptual illustration showing how violin width represents the density of observations.

3. Understanding Data Density

A violin plot uses kernel density estimation (KDE) to estimate the probability density of numerical observations. KDE creates a smooth curve representing where values are concentrated.

The estimated density is mirrored around a central position to create the violin shape. This is why the chart looks similar to a violin instrument.

Understanding Width

A wider part of the violin means many observations are concentrated around that range. A narrow part means relatively fewer observations are present.

Wide Region
    = Higher estimated density

Narrow Region
    = Lower estimated density
Remember: Violin width represents estimated probability density, not the actual number of observations directly.

4. Import Matplotlib and NumPy

We use Matplotlib to create violin plots and NumPy to generate numerical sample data.

import matplotlib.pyplot as plt
import numpy as np

The plt.violinplot() function creates a violin plot from one or more numerical datasets.

5. Creating a Basic Violin Plot

To create a basic violin plot, pass a numerical dataset to plt.violinplot().

Example

import matplotlib.pyplot as plt

marks = [
    45, 50, 52, 55, 58, 60,
    62, 65, 68, 70, 72, 75
]

plt.violinplot(marks)

plt.title("Student Marks Distribution")
plt.ylabel("Marks")

plt.show()

Expected Output

Student Marks Distribution

A violin-shaped distribution is displayed.

The shape represents the estimated density
of student marks across the dataset.
Tip: Violin plots are especially useful when you want to understand the shape of a data distribution, not only its median and quartiles.

6. Creating Multiple Violin Plots

You can compare multiple datasets by passing a list of datasets to plt.violinplot().

import matplotlib.pyplot as plt

class_a = [45, 50, 55, 60, 65, 70, 75]
class_b = [50, 55, 60, 65, 70, 75, 80]
class_c = [40, 45, 50, 55, 60, 65, 70]

data = [class_a, class_b, class_c]

plt.violinplot(data)

plt.title("Comparison of Student Marks")
plt.ylabel("Marks")

plt.xticks(
    [1, 2, 3],
    ["Class A", "Class B", "Class C"]
)

plt.show()

Expected Output

Comparison of Student Marks

Three violin plots are displayed:

Violin 1 = Class A
Violin 2 = Class B
Violin 3 = Class C

Each violin represents the distribution
of marks for its respective class.

Why use multiple violin plots?

Multiple violin plots help compare the distribution shape, density, spread and concentration of different datasets.

7. Adding Labels to Violin Plots

Use plt.xticks() to display category names below each violin plot. This makes multiple datasets easier to identify.

import matplotlib.pyplot as plt

group_a = [20, 25, 30, 35, 40, 45, 50]
group_b = [30, 35, 40, 45, 50, 55, 60]

data = [group_a, group_b]

plt.violinplot(data)

plt.xticks(
    [1, 2],
    ["Group A", "Group B"]
)

plt.title("Group Distribution")
plt.ylabel("Values")

plt.show()

Expected Output

Group Distribution

Two violin plots are displayed.

Group A
Group B

Each violin is identified by its category label.

8. Displaying Mean and Median

Matplotlib provides the showmeans and showmedians parameters to display statistical indicators on violin plots.

import matplotlib.pyplot as plt

marks = [
    45, 50, 52, 55, 58, 60,
    62, 65, 68, 70, 72, 75
]

plt.violinplot(
    marks,
    showmeans=True,
    showmedians=True
)

plt.title("Violin Plot with Mean and Median")
plt.ylabel("Marks")

plt.show()

Expected Output

Violin Plot with Mean and Median

A violin plot is displayed with:
- Estimated data distribution
- Mean indicator
- Median indicator
Remember: The mean is the arithmetic average. The median is the middle value of sorted observations.

9. Displaying Minimum and Maximum Values

The showextrema parameter controls whether the minimum, maximum and central range indicators are displayed on the violin plot.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80]

plt.violinplot(
    marks,
    showextrema=True
)

plt.title("Violin Plot with Extrema")
plt.ylabel("Marks")

plt.show()

Expected Output

Violin Plot with Extrema

The violin plot displays:
- Minimum value
- Maximum value
- Central statistical indicator

Hiding Extrema

plt.violinplot(
    marks,
    showextrema=False
)

Expected Output

The violin shape is displayed without
the minimum, maximum and central range lines.

10. Displaying Quartiles with showquartiles

The showquartiles parameter controls whether the first, second and third quartile indicators are displayed.

import matplotlib.pyplot as plt

marks = [
    45, 50, 52, 55, 58, 60,
    62, 65, 68, 70, 72, 75
]

plt.violinplot(
    marks,
    showquartiles=True
)

plt.title("Violin Plot with Quartiles")
plt.ylabel("Marks")

plt.show()

Expected Output

Violin Plot with Quartiles

A violin plot is displayed with:
- First quartile (Q1)
- Median (Q2)
- Third quartile (Q3)
Tip: Quartile indicators help combine information about the density shape with useful statistical summary values.

11. Customizing Violin Plot Colours

The plt.violinplot() function returns a dictionary of graphical components. You can use the returned bodies collection to customize violin colours.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75]

fig, ax = plt.subplots()

result = ax.violinplot(marks)

for body in result["bodies"]:
    body.set_facecolor("#93c5fd")
    body.set_edgecolor("#1d4ed8")
    body.set_alpha(0.8)

ax.set_title("Colored Violin Plot")
ax.set_ylabel("Marks")

plt.show()

Expected Output

Colored Violin Plot

The violin body is filled with light blue.
The violin border is dark blue.
The transparency is set to 0.8.

Common Styling Methods

Method Purpose
set_facecolor() Changes the violin fill colour.
set_edgecolor() Changes the violin border colour.
set_alpha() Controls transparency.
set_linewidth() Changes border line thickness.

12. Applying Different Colours to Multiple Violins

You can assign different colours to individual violin bodies using a loop.

import matplotlib.pyplot as plt

class_a = [45, 50, 55, 60, 65, 70, 75]
class_b = [50, 55, 60, 65, 70, 75, 80]
class_c = [40, 45, 50, 55, 60, 65, 70]

data = [class_a, class_b, class_c]

fig, ax = plt.subplots()

result = ax.violinplot(data)

colors = [
    "#93c5fd",
    "#86efac",
    "#fcd34d"
]

for body, color in zip(result["bodies"], colors):
    body.set_facecolor(color)
    body.set_edgecolor("#334155")
    body.set_alpha(0.85)

ax.set_xticks(
    [1, 2, 3],
    ["Class A", "Class B", "Class C"]
)

ax.set_title("Colored Class Comparison")
ax.set_ylabel("Marks")

plt.show()

Expected Output

Colored Class Comparison

Class A = Light Blue
Class B = Light Green
Class C = Light Yellow

Three differently coloured violin plots are displayed.

13. Creating Horizontal Violin Plots

By default, violin plots are vertical. You can create horizontal violin plots using the orientation="horizontal" parameter.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80]

plt.violinplot(
    marks,
    orientation="horizontal"
)

plt.title("Horizontal Violin Plot")
plt.xlabel("Marks")

plt.show()

Expected Output

Horizontal Violin Plot

A horizontal violin shape is displayed.
The numerical values are represented along
the X-axis.
Tip: Horizontal violin plots can be useful when displaying several categories or when the chart layout requires a horizontal arrangement.

14. Controlling Violin Width

The widths parameter controls the maximum width of the violin bodies. It can be useful when displaying multiple violin plots.

import matplotlib.pyplot as plt

data = [
    [45, 50, 55, 60, 65, 70, 75],
    [50, 55, 60, 65, 70, 75, 80],
    [40, 45, 50, 55, 60, 65, 70]
]

plt.violinplot(
    data,
    widths=0.5
)

plt.title("Violin Plot with Custom Width")

plt.xticks(
    [1, 2, 3],
    ["Group A", "Group B", "Group C"]
)

plt.ylabel("Values")

plt.show()

Expected Output

Violin Plot with Custom Width

Three violin plots are displayed.
Each violin uses a maximum width setting of 0.5.

15. Understanding Bandwidth with bw_method

The bw_method parameter controls the bandwidth used by the kernel density estimation process. Bandwidth influences how smooth or detailed the violin shape appears.

import matplotlib.pyplot as plt
import numpy as np

data = np.random.normal(
    loc=50,
    scale=10,
    size=100
)

plt.violinplot(
    data,
    bw_method=0.5
)

plt.title("Violin Plot with Custom Bandwidth")
plt.ylabel("Values")

plt.show()

Expected Output

Violin Plot with Custom Bandwidth

A violin plot is displayed using a bandwidth
setting of 0.5.

The bandwidth affects the smoothness
of the estimated density shape.

Bandwidth Comparison

Bandwidth Effect
Smaller bandwidth Can show more local detail and variation.
Larger bandwidth Produces a smoother density estimate.
Important: The exact appearance depends on the dataset and the density estimation method. Avoid choosing a bandwidth only to make the plot look attractive.

16. Understanding Violin Plot Components

The violin plot function returns several graphical components that can be customized individually.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75]

fig, ax = plt.subplots()

result = ax.violinplot(
    marks,
    showmeans=True,
    showmedians=True,
    showextrema=True
)

print(result.keys())

plt.show()

Expected Output

dict_keys([
    'bodies',
    'cmeans',
    'cmaxes',
    'cmins',
    'cbars',
    'cmedians'
])

The returned dictionary provides access to the violin bodies, mean indicators, maximum and minimum indicators, central range lines and median indicators. Exact available components depend on the selected options and Matplotlib version.

Component Description
bodies The filled violin shapes.
cmeans Mean indicator collection.
cmedians Median indicator collection.
cmins Minimum indicator collection.
cmaxes Maximum indicator collection.
cbars Central range line collection.

17. Difference Between Box Plot and Violin Plot

Box plots and violin plots are both used to understand numerical data distributions. However, they display different levels of information.

Box Plot Violin Plot
Shows quartiles and median. Shows estimated probability density.
Uses a rectangular box. Uses a density-shaped body.
Summarizes the five-number distribution. Shows the shape of the distribution.
Does not directly show density shape. Shows where observations are concentrated.
Usually easier to interpret. Provides more detail about distribution shape.

When should you use each chart?

Use a box plot when you want a compact summary of the median, quartiles and possible outliers. Use a violin plot when you want to understand the shape and density of the distribution.

18. Violin Plots Using the Object-Oriented API

Matplotlib also supports an object-oriented approach. Instead of calling plt.violinplot() directly, create a Figure and Axes object and use ax.violinplot().

import matplotlib.pyplot as plt
import numpy as np

data = [
    np.random.normal(50, 10, 100),
    np.random.normal(60, 12, 100),
    np.random.normal(70, 8, 100)
]

fig, ax = plt.subplots(figsize=(8, 5))

result = ax.violinplot(
    data,
    showmeans=True,
    showmedians=True
)

ax.set_xticks(
    [1, 2, 3],
    ["Group A", "Group B", "Group C"]
)

ax.set_title("Group Distribution Comparison")
ax.set_ylabel("Values")

plt.show()

Expected Output

Group Distribution Comparison

Three violin plots are displayed.

Group A = Mean around 50
Group B = Mean around 60
Group C = Mean around 70

Each violin displays its estimated distribution,
mean indicator and median indicator.
Tip: The generated values may vary because the example uses random data. The displayed distribution will not be exactly identical every time.

19. Important Parameters of plt.violinplot()

Parameter Description Example
dataset Input numerical data. plt.violinplot(data)
positions Controls the positions of violin plots. positions=[1, 2, 3]
vert Controls orientation in older versions. vert=False
orientation Controls plot orientation. orientation="horizontal"
showmeans Displays the mean indicator. showmeans=True
showmedians Displays the median indicator. showmedians=True
showextrema Displays minimum and maximum indicators. showextrema=True
showquartiles Displays quartile indicators. showquartiles=True
widths Controls maximum violin width. widths=0.5
bw_method Controls density estimation bandwidth. bw_method=0.5
points Controls the number of points used to evaluate density. points=100
quantiles Displays specified quantile positions. quantiles=[[0.25, 0.5, 0.75]]
Version Note: Some parameters, including orientation-related options and quartile display behaviour, vary across Matplotlib versions. Check the installed version's documentation when a parameter is not recognized.

20. Practical Example: Employee Salary Distribution

Let's create violin plots to compare the salary distribution of employees from three departments. We will display mean and median indicators and customize the violin colours.

Complete Python Program

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(10)

it_department = np.random.normal(
    loc=60000,
    scale=10000,
    size=100
)

hr_department = np.random.normal(
    loc=45000,
    scale=7000,
    size=100
)

sales_department = np.random.normal(
    loc=50000,
    scale=12000,
    size=100
)

data = [
    it_department,
    hr_department,
    sales_department
]

fig, ax = plt.subplots(figsize=(9, 6))

result = ax.violinplot(
    data,
    showmeans=True,
    showmedians=True,
    showextrema=True
)

colors = [
    "#93c5fd",
    "#86efac",
    "#fcd34d"
]

for body, color in zip(result["bodies"], colors):
    body.set_facecolor(color)
    body.set_edgecolor("#334155")
    body.set_alpha(0.85)

ax.set_xticks(
    [1, 2, 3],
    ["IT", "HR", "Sales"]
)

ax.set_title("Employee Salary Distribution")
ax.set_xlabel("Departments")
ax.set_ylabel("Salary")

ax.grid(axis="y", linestyle="--", alpha=0.4)

plt.show()

Expected Output

Employee Salary Distribution

IT Department     : Blue Violin
HR Department     : Green Violin
Sales Department  : Yellow Violin

Each violin displays the estimated salary distribution,
mean indicator, median indicator and extrema.

The chart helps compare salary concentration
and variation across departments.

Understanding the Result

The IT department has a higher average salary in this example. The HR and Sales departments show different distributions and spreads. The violin shapes help understand where employee salaries are concentrated.

21. Best Practices for Violin Plots

  • Use violin plots when distribution shape is important.
  • Compare datasets using consistent scales.
  • Use clear category labels.
  • Display median and mean when useful.
  • Choose a suitable bandwidth for density estimation.
  • Avoid too many violin plots in one chart.
  • Use colours that are easy to distinguish.
  • Explain that violin width represents estimated density.
Important: A violin plot is based on a density estimate. Its shape can change with the bandwidth and sample size. Always consider the dataset before interpreting the displayed shape.

22. Common Mistakes and Solutions

Common Mistake Solution
Passing incorrectly structured data. Pass numerical observations as a dataset or sequence of datasets.
Violin colours are not visible. Customize the returned bodies collection.
Mean indicator is missing. Set showmeans=True.
Median indicator is missing. Set showmedians=True.
Density shape looks too smooth. Review the bandwidth setting.
Category names are missing. Use plt.xticks() or Axes tick methods.
Orientation parameter is not recognized. Check the installed Matplotlib version.

23. Practice Questions

Beginner Level

  1. What is a violin plot?
  2. Which Matplotlib function creates violin plots?
  3. What does the width of a violin represent?
  4. What is probability density?
  5. What is kernel density estimation?

Intermediate Level

  1. Explain the difference between a box plot and violin plot.
  2. What is the purpose of bw_method?
  3. How can you display the mean and median?
  4. How do you customize violin colours?
  5. What is the purpose of showextrema?
  6. How can you create a horizontal violin plot?

Practical Tasks

  1. Create a violin plot for student examination marks.
  2. Compare three different classes using violin plots.
  3. Display mean and median indicators.
  4. Customize violin colours and transparency.
  5. Create a horizontal violin plot.
  6. Compare employee salary distributions across departments.

Summary

A violin plot is a statistical chart used to visualize numerical data distribution. It combines information about probability density with useful statistical indicators. Wider areas represent higher estimated data density, while narrower areas represent lower estimated density.

Matplotlib provides the plt.violinplot() function to create violin plots. It supports multiple datasets, horizontal orientation, mean and median indicators, extrema and quartile information.

The appearance of violin plots can be customized using the returned bodies collection. Parameters such as widths, bw_method and points help control the appearance and density estimation process.

Violin plots are useful when you need to understand the shape of a distribution and compare different datasets. They provide more information about density shape than a standard box plot.