0
0
Matplotlibdata~30 mins

Box plot vs violin plot comparison in Matplotlib - Hands-On Comparison

Choose your learning style9 modes available
Box plot vs violin plot comparison
📖 Scenario: You work as a data analyst for a company that wants to understand the distribution of sales data across different regions. You will use two common plots: box plot and violin plot, to compare the sales data visually.
🎯 Goal: Create a Python program using matplotlib to plot both a box plot and a violin plot side by side for the sales data of three regions. This will help you see how these plots show data distribution differently.
📋 What You'll Learn
Create a dictionary called sales_data with three keys: 'North', 'South', and 'East' and their sales values as lists of numbers.
Create a list called regions containing the region names in order: 'North', 'South', 'East'.
Use matplotlib.pyplot to create a figure with two subplots side by side.
Plot a box plot of the sales data on the first subplot using ax1.boxplot().
Plot a violin plot of the sales data on the second subplot using ax2.violinplot().
Set the x-axis tick labels to the region names for both plots.
Add titles to each subplot: 'Box Plot' and 'Violin Plot'.
Display the plots using plt.show().
💡 Why This Matters
🌍 Real World
Data analysts often compare different visualizations to understand data distribution and variability across groups or regions.
💼 Career
Knowing how to create and interpret box plots and violin plots is essential for data scientists and analysts to communicate insights effectively.
Progress0 / 4 steps
1
Create the sales data dictionary
Create a dictionary called sales_data with these exact entries: 'North': [250, 270, 300, 280, 260], 'South': [220, 210, 230, 240, 225], and 'East': [300, 320, 310, 305, 315].
Matplotlib
Need a hint?

Use curly braces {} to create the dictionary and colons : to assign lists to each region key.

2
Create the regions list
Create a list called regions containing the strings 'North', 'South', and 'East' in this exact order.
Matplotlib
Need a hint?

Use square brackets [] to create the list and separate the region names with commas.

3
Plot box plot and violin plot side by side
Import matplotlib.pyplot as plt. Create a figure and two subplots side by side using plt.subplots(1, 2, figsize=(10, 5)). On the first subplot ax1, plot a box plot of the sales data values using ax1.boxplot(). On the second subplot ax2, plot a violin plot of the sales data values using ax2.violinplot(). Set the x-axis tick labels to regions for both plots. Add titles 'Box Plot' and 'Violin Plot' to ax1 and ax2 respectively.
Matplotlib
Need a hint?

Use list comprehension to get the sales values in order for plotting. Use set_xticklabels to label x-axis ticks. Remember violin plot x-ticks start at 1.

4
Display the plots
Add a line to display the plots using plt.show().
Matplotlib
Need a hint?

Use plt.show() to display the figure with both plots.