0
0
Matplotlibdata~30 mins

Small multiples (facet grid) in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Create Small Multiples (Facet Grid) with Matplotlib
📖 Scenario: You are a data analyst at a fruit store. You have sales data for different fruits over several months. You want to compare the monthly sales of each fruit side by side to see trends easily.
🎯 Goal: Build a small multiples (facet grid) plot using matplotlib to show monthly sales for each fruit in separate subplots.
📋 What You'll Learn
Create a dictionary with fruit names as keys and lists of monthly sales as values.
Create a list of month names to use as x-axis labels.
Use a configuration variable to store the number of fruits.
Use a loop to create subplots for each fruit.
Plot monthly sales data for each fruit in its own subplot.
Add titles to each subplot with the fruit name.
Display the final figure with all subplots.
💡 Why This Matters
🌍 Real World
Small multiples help compare different groups or categories side by side, making it easier to spot patterns or differences in data over time or conditions.
💼 Career
Data analysts and scientists often use facet grids to visualize segmented data clearly, which helps in reporting and decision-making.
Progress0 / 4 steps
1
Create the sales data dictionary and months list
Create a dictionary called fruit_sales with these exact entries: 'Apple': [30, 35, 40, 45], 'Banana': [20, 25, 30, 35], 'Cherry': [15, 18, 20, 22]. Also create a list called months with these exact values: 'Jan', 'Feb', 'Mar', 'Apr'.
Matplotlib
Need a hint?

Use curly braces {} to create the dictionary and square brackets [] for the lists.

2
Create a variable for the number of fruits
Create a variable called num_fruits and set it to the number of keys in the fruit_sales dictionary.
Matplotlib
Need a hint?

Use the len() function to count the keys in the dictionary.

3
Create subplots and plot each fruit's sales
Import matplotlib.pyplot as plt. Use plt.subplots() with num_fruits rows and 1 column to create subplots. Use a for loop with variables index and fruit from enumerate(fruit_sales) to plot each fruit's sales on its subplot. Use ax.plot(months, fruit_sales[fruit]) to plot. Set the subplot title with ax.set_title(fruit). Use plt.tight_layout() to adjust spacing.
Matplotlib
Need a hint?

Remember to handle the case when there is only one subplot (axes is not a list).

4
Display the final figure
Use plt.show() to display the figure with all the subplots.
Matplotlib
Need a hint?

Use plt.show() to display the figure window.