Advanced Matplotlib: Beyond the Basics

Advanced Matplotlib: Beyond the Basics in Python: You already know how to make a basic line chart. But professional data reports need more.

Concept Explanation

You already know how to make a basic line chart. But professional data reports need more. They need Subplots (multiple charts in one image), Secondary Axes (comparing two different scales, like temperature and humidity), and Annotations (pointing out specific data points).

Matplotlib is a "low-level" library, which means you have to write more code, but you have 100% control over every pixel on the screen.


Syntax or Core Structure

Subplots (Figures and Axes)

The most professional way to use Matplotlib is the "Object-Oriented" style, where you create a fig (the whole window) and ax (the individual chart).

import matplotlib.pyplot as plt

# Create a layout with 1 row and 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

ax1.plot([1, 2, 3], [10, 20, 30], color="red")
ax1.set_title("First Chart")

ax2.bar(["A", "B", "C"], [5, 15, 10])
ax2.set_title("Second Chart")

plt.tight_layout() # Prevents charts from overlapping
plt.show()

Code Example #1 (Basic)

Adding multiple lines and a legend.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]  # Squares
y2 = [1, 8, 27, 64, 125] # Cubes

plt.plot(x, y1, label="Squared", marker='o')
plt.plot(x, y2, label="Cubed", marker='s')

plt.title("Math Comparison")
plt.legend() # Crucial: Makes the labels visible
plt.show()

Code Example #2 (Intermediate)

Customizing Ticks and Grids.

import matplotlib.pyplot as plt

plt.plot([0, 10, 20, 30], [5, 2, 8, 1])

# Customize the spacing of numbers on the axis
plt.xticks([0, 15, 30], ["Start", "Middle", "End"])
plt.grid(True, linestyle='--', alpha=0.6) # Alpha = Transparency

plt.show()

Real World Example

Financial Performance Dashboard: Showing Revenue as a bar chart and Profit Margin as a line chart on the same graph.

# 🏢 Logic Summary
# 1. Use ax.twinx() to create a second Y-axis.
# 2. Plot Revenue on the left axis and Profit % on the right.
# 3. Use different colors so the user doesn't get confused.

Common Mistakes

  1. Overlapping Labels: If you have many charts, their titles often crash into each other. Always use plt.tight_layout().
  2. Hard-to-read Colors: Using light yellow or neon green on a white background. Stick to standard colors like "tab:blue", "darkred", or "gold".
  3. No Context: Sharing a chart without units (e.g., "Price" instead of "Price (USD)").

Best Practices

  • Save as PDF/SVG: For printing or high-quality reports, use plt.savefig("chart.pdf"). It's sharper than a PNG.
  • Use Style Sheets: plt.style.use('bmh') or plt.style.use('fivethirtyeight') makes your charts look professionally designed instantly.
  • Handle Large Data: If you have 1 million points, don't plot them all! Use a "Scatter" plot with a small s (size) or downsample your data first.

Practice Exercises

  1. The Grid Master: Create a 2x2 grid of charts. Each chart must show a different type of plot: Line, Bar, Scatter, and Histogram.
  2. The Annotator: Create a line chart of 5 random numbers. Use plt.annotate() to point an arrow at the highest number with the text "Peak Value".
  3. The Twin Axis: Plot the "Number of Sales" (0 to 1,000) and the "Total Profit" (0 to $50,000) on the same chart using a secondary Y-axis.