Matplotlib β Figures and Axes
After completing this topic, you will be able to:
Understand the Figure/Axes structure in matplotlib and create basic graphs on your own.
What is Matplotlib?
Matplotlib is a library for creating graphs and charts in Python. When you look at data visually, you can see patterns much more easily than when you just look at numbers.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]y = [2, 4, 6, 8, 10]
plt.plot(x, y)plt.show()plt is the conventional abbreviation for matplotlib.pyplot.
Figure and Axes
The core structure of matplotlib consists of two main components:
Figure (Canvas)
βββ Axes (Graph area)
βββ x-axis
βββ y-axis
βββ Title
βββ Data (lines, bars, points...)- Figure: The overall drawing area. Like a canvas.
- Axes: The space where the actual graph is drawn. You can place multiple Axes within a single Figure.
import matplotlib.pyplot as plt
# Explicitly create a Figure and Axesfig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])ax.set_title("My First Plot")ax.set_xlabel("X axis")ax.set_ylabel("Y axis")
plt.show()plt.subplots() creates both the Figure and Axes simultaneously. This approach is highly recommended.
Line Plot
Used to show changes over time.
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May"]sales = [100, 120, 90, 150, 130]
fig, ax = plt.subplots(figsize=(8, 5))ax.plot(months, sales, marker="o", color="blue", linewidth=2)ax.set_title("Monthly Sales")ax.set_ylabel("Sales")ax.grid(True, alpha=0.3)
plt.show()marker="o": Displays a circle at each data point.figsize=(8, 5): Width 8 inches, height 5 inches.grid(True): Displays grid lines.
Bar Chart
Used for comparing categories.
import matplotlib.pyplot as plt
languages = ["Python", "JS", "Java", "C++"]users = [30, 25, 20, 15]
fig, ax = plt.subplots()ax.bar(languages, users, color=["#3776AB", "#F7DF1E", "#B07219", "#00599C"])ax.set_title("Programming Language Popularity")ax.set_ylabel("Users (%)")
plt.show()You can specify a list of colors to ax.bar() to assign different colors to each bar.
Scatter Plot
Shows the relationship between two variables.
import matplotlib.pyplot as pltimport numpy as np
np.random.seed(42)x = np.random.randn(50)y = 2 * x + np.random.randn(50) * 0.5
fig, ax = plt.subplots()ax.scatter(x, y, alpha=0.7, color="coral")ax.set_title("Scatter Plot Example")ax.set_xlabel("X")ax.set_ylabel("Y")
plt.show()alpha=0.7 is the transparency. Useful when many points overlap.
Multiple Graphs at Once
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
# First: Line plotaxes[0].plot([1, 2, 3], [1, 4, 9])axes[0].set_title("Line")
# Second: Bar chartaxes[1].bar(["A", "B", "C"], [5, 3, 7])axes[1].set_title("Bar")
# Third: Scatter plotaxes[2].scatter([1, 2, 3, 4], [4, 1, 3, 2])axes[2].set_title("Scatter")
plt.tight_layout()plt.show()plt.subplots(1, 3) creates a subplot with 1 row and 3 columns. tight_layout() automatically adjusts the spacing between graphs to prevent overlapping.
Saving
# Save to a file instead of displaying on the screenfig.savefig("chart.png", dpi=150, bbox_inches="tight")dpi=150: Resolution (default 100)bbox_inches="tight": Automatically adjusts margins- Supported formats: PNG, PDF, SVG, JPG