Box plots and violin plots help us understand data by showing its spread and shape. They make it easy to see patterns and differences in data.
0
0
Box plot vs violin plot comparison in Matplotlib
Introduction
When you want to quickly see the range and middle of your data.
When you want to understand the distribution shape of your data.
When comparing multiple groups side by side.
When you want to spot outliers in your data.
When you want a detailed view of data density along with summary statistics.
Syntax
Matplotlib
import matplotlib.pyplot as plt # Box plot plt.boxplot(data) # Violin plot plt.violinplot(data)
Both plots need your data as input, usually a list or array of numbers.
Box plot shows median, quartiles, and outliers. Violin plot shows data density and distribution shape.
Examples
Simple box plot for a small list of numbers.
Matplotlib
plt.boxplot([1, 2, 3, 4, 5])
Simple violin plot for the same list to see distribution shape.
Matplotlib
plt.violinplot([1, 2, 3, 4, 5])
Box plots for two groups side by side.
Matplotlib
plt.boxplot([[1, 2, 3], [4, 5, 6]])
Violin plots for two groups side by side.
Matplotlib
plt.violinplot([[1, 2, 3], [4, 5, 6]])
Sample Program
This code creates two groups of random data. It shows a box plot and a violin plot side by side to compare how each visualizes the data.
Matplotlib
import matplotlib.pyplot as plt import numpy as np # Create sample data for two groups np.random.seed(0) group1 = np.random.normal(0, 1, 100) group2 = np.random.normal(2, 0.5, 100) data = [group1, group2] plt.figure(figsize=(10, 5)) # Box plot plt.subplot(1, 2, 1) plt.boxplot(data) plt.title('Box Plot') plt.xticks([1, 2], ['Group 1', 'Group 2']) # Violin plot plt.subplot(1, 2, 2) plt.violinplot(data) plt.title('Violin Plot') plt.xticks([1, 2], ['Group 1', 'Group 2']) plt.tight_layout() plt.show()
OutputSuccess
Important Notes
Box plots are great for quick summary and spotting outliers.
Violin plots give more detail about data shape and density.
Use both together to get a full picture of your data.
Summary
Box plots show median, quartiles, and outliers clearly.
Violin plots show the full distribution shape and density.
Both help compare groups and understand data spread.