0
0
Matplotlibdata~5 mins

Violin plot with plt.violinplot in Matplotlib

Choose your learning style9 modes available
Introduction

A violin plot helps you see the shape of data distribution clearly. It shows where data points are dense or sparse.

Comparing the distribution of test scores between two classes.
Visualizing the spread of daily temperatures over a month.
Checking the distribution of sales amounts across different stores.
Understanding the variation in heights of plants in different gardens.
Syntax
Matplotlib
plt.violinplot(dataset, positions=None, widths=0.5, showmeans=False, showmedians=False, showextrema=True)

dataset is a list or array of data points or multiple datasets.

positions sets where violins appear on the x-axis.

Examples
Basic violin plot for one dataset.
Matplotlib
plt.violinplot([data])
Violin plots for two datasets side by side.
Matplotlib
plt.violinplot([data1, data2], positions=[1, 2])
Show median line inside the violin.
Matplotlib
plt.violinplot(data, showmedians=True)
Sample Program

This code creates two groups of random numbers with different centers and spreads. It then draws violin plots side by side with median lines shown. Labels and title help understand the plot.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create two sets of random data
np.random.seed(0)
data1 = np.random.normal(0, 1, 100)
data2 = np.random.normal(2, 0.5, 100)

# Draw violin plots
plt.violinplot([data1, data2], positions=[1, 2], showmedians=True)

# Add labels and title
plt.xticks([1, 2], ['Group 1', 'Group 2'])
plt.title('Violin Plot Example')
plt.ylabel('Value')

plt.show()
OutputSuccess
Important Notes

Violin plots combine box plot and kernel density estimation to show data distribution.

Use showmeans=True to add mean markers.

Adjust widths to change violin thickness.

Summary

Violin plots show data distribution shape and spread.

Use plt.violinplot() with data to create them.

Options let you show medians, means, and control appearance.