When I first started doing data visualization in Python, Matplotlib felt like a giant, intimidating library. But once you break it down, it's just a set of simple rules. This is my personal cheat sheet for line plots, bar charts, and the math behind stacking.
Part 1: The Foundation (Line Plots)
The core of Matplotlib is plt.plot(x, y). You can layer multiple lines on top of each other, give them custom styles, and add a legend.
from matplotlib import pyplot as plt
# Customizing lines
plt.plot(ages_x, py_dev_y, label='Python', color='blue', linewidth=2)
plt.plot(ages_x, js_dev_y, label='JavaScript', color='orange')
# Dashed line, custom hex color
plt.plot(ages_x, dev_y, color='#444444', linestyle='--', label='All Devs')
plt.xlabel('Ages')
plt.ylabel('Median Salary (USD)')
plt.title('Median Salary by Age')
plt.legend() # Must be called after plots to gather labels
plt.tight_layout() # Prevents labels from getting cut off
plt.savefig('plot.png') # ALWAYS call savefig BEFORE show()
plt.show()
The Trap of `plt.ylim`
If you are plotting test scores that range from 45% to 92%, Matplotlib will automatically zoom in on that range. This can be misleading. If the y-axis starts at 45, a 10-point improvement looks like a massive cliff.
Rule of thumb: If your data is a percentage or ratio, always use plt.ylim(0, 100) to show the full context.
Drawing Reference Lines
Sometimes you need to draw attention to a specific threshold. plt.axvline() draws a vertical line, and plt.axhline() draws a horizontal line.
# Draw a dotted grey line at x=1.5
plt.axvline(x=1.5, linestyle=':', color='gray', label='Crossover')
Part 2: Subplots
Instead of making two separate windows, you can put multiple charts in one figure. This is called a subplot.
# 1 row, 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(x, y)
ax1.set_title('Left Chart')
ax2.plot(x, z)
ax2.set_title('Right Chart')
plt.tight_layout()
plt.show()
Note: When using subplots, use the `ax` methods (e.g., `ax1.axhline()`) instead of the global `plt` methods so the line goes to the correct chart.
Part 3: Bar Charts & CSVs
Loading data from a CSV is best done with csv.DictReader. Once you have your lists, plt.bar() makes vertical bars and plt.barh() makes horizontal bars.
import csv
import matplotlib.pyplot as plt
with open('data.csv') as f:
csv_reader = csv.DictReader(f)
ages, py_salaries, js_salaries = [], [], []
for row in csv_reader:
# Remember to convert strings to integers!
ages.append(int(row['Age']))
py_salaries.append(int(row['Python']))
js_salaries.append(int(row['JavaScript']))
plt.bar(ages, py_salaries, label='Python')
Part 4: The Art of Stacking
A stacked bar chart shows parts of a whole. The trick is the bottom parameter.
For the first layer, it sits on the ground (0). For the second layer, the bottom parameter must be set to the height of the first layer. For the third layer, bottom is the sum of the first and second layers.
# Layer 1
bars1 = plt.bar(x, data1, width, label='Bottom')
# Layer 2 sits on Layer 1
bars2 = plt.bar(x, data2, width, bottom=data1, label='Top')
Centering Text inside Stacked Bars
This is the hardest part visually. If you use plt.text(), you can't just put the text at the height of the bar. You have to calculate the exact center of the segment.
The math is: Sum of previous segments + (Current segment height / 2).
for i, bar in enumerate(bars2):
height = bar.get_height()
bottom_height = data1[i] # Height of the bar below it
# Calculate the exact center of the top bar
y_center = bottom_height + (height / 2)
# Get the x-center of the bar
x_center = bar.get_x() + bar.get_width() / 2
plt.text(x_center, y_center, str(height), ha='center', va='center', color='white')
"Data visualization isn't just about making things look pretty. It's about ensuring the viewer isn't misled by a skewed y-axis or an overlapping label."
Tharana Nimsara
✅ VERIFIED AUTHOR
SHA256: 4e9b2a...c11d