Advanced Python Data Visualization
Matplotlib Basics
The Anatomy of a Plot
Before you can create a plot with Matplotlib, it helps to understand its basic structure. Think of it like a painting. Every plot starts with a Figure, which is the entire canvas or window that holds everything. It's the blank space you're about to draw on.
Inside the Figure, you have one or more Axes. This isn't the plural of 'axis' (like x and y); it's the actual plot area where your data points are drawn. You can have a single Axes object that fills the whole figure, or multiple Axes objects to create a grid of subplots. For now, we'll stick to one.
So, the hierarchy is simple: The Figure is the container, and the Axes is the content.
This structure gives you a lot of control. You can change the size of the figure, add text anywhere on it, and arrange multiple plots exactly how you want them. But for basic plotting, Matplotlib often handles creating the Figure and Axes for you automatically.
Creating Your First Plots
Let's start by making a few common types of plots. We'll use a module from Matplotlib called pyplot, which is conventionally imported as plt. This interface makes plotting straightforward.
A line chart is perfect for showing a trend over time or a continuous sequence. You provide x and y coordinates, and Matplotlib connects the dots.
import matplotlib.pyplot as plt
# Data for our line chart
year = [2018, 2019, 2020, 2021, 2022]
stock_price = [100, 120, 90, 150, 180]
# Create the plot
plt.plot(year, stock_price)
# Display the plot
plt.show()
What if you don't want to connect the points? If you want to see the relationship between two different variables, a scatter plot is a better choice. It shows each data point as an individual dot, making it easy to spot clusters or patterns.
import matplotlib.pyplot as plt
# Data for our scatter plot
study_hours = [2, 3, 5, 6, 8]
exam_score = [65, 70, 80, 82, 95]
# Create the scatter plot
plt.scatter(study_hours, exam_score)
# Display the plot
plt.show()
Finally, let's look at bar charts. These are great for comparing quantities across different categories. Instead of plotting individual points, you're showing the magnitude of each category as a bar.
import matplotlib.pyplot as plt
# Data for our bar chart
products = ['A', 'B', 'C', 'D']
sales = [350, 420, 280, 510]
# Create the bar chart
plt.bar(products, sales)
# Display the plot
plt.show()
Making Plots Readable
A plot without labels is just a picture. To turn it into a useful visualization, you need to add context. Matplotlib makes it easy to add titles, axis labels, and legends to explain what your data represents.
Let's take our stock price chart and make it publication-ready. We'll add a title to tell viewers the plot's subject, labels for the x and y axes to explain the units, and change the color to make it visually distinct.
import matplotlib.pyplot as plt
# Data for our plot
year = [2018, 2019, 2020, 2021, 2022]
stock_price = [100, 120, 90, 150, 180]
# Create the plot and customize it
plt.plot(year, stock_price, color='green', linestyle='--')
# Add a title and labels
plt.title('Stock Price Over Time')
plt.xlabel('Year')
plt.ylabel('Price (💲)')
# Display the plot
plt.show()
Notice how we used arguments like color and linestyle right inside the plot function. Many functions in Matplotlib have optional arguments for customization.
What if you have multiple datasets on one plot? A legend is essential. It adds a key to help viewers distinguish between different lines or sets of points. You add a label to each dataset you plot, then call plt.legend() to display them.
import matplotlib.pyplot as plt
# Data for two companies
year = [2018, 2019, 2020, 2021, 2022]
company_a_price = [100, 120, 90, 150, 180]
company_b_price = [80, 85, 110, 130, 140]
# Plot both datasets with labels
plt.plot(year, company_a_price, label='Company A')
plt.plot(year, company_b_price, label='Company B')
# Add title and labels
plt.title('Stock Prices for Two Companies')
plt.xlabel('Year')
plt.ylabel('Price (💲)')
# Add the legend
plt.legend()
# Display the plot
plt.show()
With these simple commands, you can turn a basic plot into a clear and informative graphic.
Ready to check your understanding?
In the Matplotlib hierarchy, what is the relationship between a Figure and an Axes?
Which type of plot is most suitable for comparing the sales figures of five different products in a single month?
These building blocks are the foundation for creating nearly any static visualization you can imagine. As you get more comfortable, you'll discover even more ways to customize and combine plots to tell powerful stories with your data.