0
0
Matplotlibdata~30 mins

Figure-level methods vs axes-level in Matplotlib - Hands-On Comparison

Choose your learning style9 modes available
Figure-level methods vs axes-level in matplotlib
📖 Scenario: You are working with sales data for three products over four months. You want to visualize this data using bar charts to compare sales.
🎯 Goal: Build two bar charts: one using figure-level methods and one using axes-level methods in matplotlib. Understand the difference between these two approaches.
📋 What You'll Learn
Create a dictionary called sales_data with product names as keys and lists of monthly sales as values
Create a list called months with the names of the four months
Create a figure and axes using plt.subplots()
Use axes-level method ax.bar() to plot sales for one product
Use figure-level method plt.bar() to plot sales for another product
Add titles and labels to both plots
Print the figure and axes objects to see their types
💡 Why This Matters
🌍 Real World
Data scientists often need to create clear and informative charts. Knowing when to use figure-level or axes-level methods helps in customizing plots effectively.
💼 Career
Understanding matplotlib's figure and axes concepts is essential for data visualization tasks in data science and analytics jobs.
Progress0 / 4 steps
1
Create the sales data and months list
Create a dictionary called sales_data with these exact entries: 'Product A': [10, 15, 7, 12], 'Product B': [5, 8, 12, 9], and 'Product C': [12, 9, 11, 14]. 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 figure and axes with plt.subplots()
Import matplotlib.pyplot as plt. Then create a figure and axes by calling plt.subplots() and assign them to variables fig and ax.
Matplotlib
Need a hint?

Use import matplotlib.pyplot as plt and then fig, ax = plt.subplots().

3
Plot sales for Product A using axes-level method and Product B using figure-level method
Use the axes-level method ax.bar() to plot sales for 'Product A' with months on the x-axis and sales on the y-axis. Then use the figure-level method plt.bar() to plot sales for 'Product B' with the same x-axis. Add titles to both plots using ax.set_title() and plt.title() respectively.
Matplotlib
Need a hint?

Use ax.bar() for Product A and plt.bar() for Product B. Add titles with ax.set_title() and plt.title().

4
Print the figure and axes objects and show the plots
Print the variables fig and ax to see their types. Then call plt.show() to display the plots.
Matplotlib
Need a hint?

Use print(fig) and print(ax) to see the figure and axes objects. Use plt.show() to display the plots.