Matplotlib
Cheatsheet
A quick reference guide for data visualization in Python using Matplotlib — covering line plots, bar charts, histograms, scatter plots, subplots, and figure customization.
📦 1. Importing & Setup
Always import matplotlib.pyplot as plt. Pair with NumPy for data generation.
import matplotlib.pyplot as plt import numpy as np # Jupyter inline display %matplotlib inline # Set default figure size globally plt.rcParams['figure.figsize'] = (10, 6) plt.rcParams['font.size'] = 12 # Check version import matplotlib print(matplotlib.__version__)
📈 2. Basic Line Plot
x = np.linspace(0, 10, 100) y = np.sin(x) plt.figure(figsize=(10, 4)) plt.plot(x, y) plt.title("Sine Wave") plt.xlabel("x") plt.ylabel("sin(x)") plt.grid(True) plt.tight_layout() plt.show()
🎨 3. Line Styles & Colors
Line style options
plt.plot(x, y, linestyle='--') # dashed plt.plot(x, y, linestyle=':') # dotted plt.plot(x, y, linestyle='-.') # dash-dot plt.plot(x, y, linestyle='-') # solid plt.plot(x, y, linewidth=2.5) # thickness plt.plot(x, y, marker='o') # circle markers
Color options
plt.plot(x, y, color='red') plt.plot(x, y, color='#1f77b4') # hex plt.plot(x, y, color='C0') # cycle # Shorthand: color + linestyle + marker plt.plot(x, y, 'r--o') # red dashed with dots plt.plot(x, y, 'b-') # blue solid plt.plot(x, y, 'g^') # green triangles
🏷️ 4. Titles & Labels
plt.title("My Chart", fontsize=16, fontweight='bold') plt.xlabel("X Axis", fontsize=12) plt.ylabel("Y Axis", fontsize=12) # Axis limits plt.xlim(0, 10) plt.ylim(-1.5, 1.5) # Tick customization plt.xticks([0, 2, 4, 6, 8, 10]) plt.yticks([-1, 0, 1]) plt.xticks(rotation=45) # Grid plt.grid(True, linestyle='--', alpha=0.5)
📌 5. Legends
# Add label in plot(), then call legend() plt.plot(x, np.sin(x), label="sin(x)") plt.plot(x, np.cos(x), label="cos(x)") plt.legend() # Location options plt.legend(loc='upper right') # best, upper left/right, lower left/right plt.legend(loc='best') # auto-placed # Style plt.legend(fontsize=10, framealpha=0.5, shadow=True)
🔵 6. Scatter Plot
x = np.random.rand(100) y = np.random.rand(100) sizes = np.random.rand(100) * 200 colors = np.random.rand(100) plt.scatter(x, y, s=sizes, c=colors, cmap='viridis', alpha=0.7, edgecolors='black', linewidths=0.5) plt.colorbar(label="Value") # show colour scale plt.title("Scatter Plot") plt.show()
📊 7. Bar Chart
Vertical bar
cats = ['A', 'B', 'C', 'D'] values = [23, 45, 12, 67] plt.bar(cats, values, color='steelblue', edgecolor='black') plt.bar(cats, values, width=0.5) # bar width plt.show()
Horizontal bar
plt.barh(cats, values, color='salmon') # Grouped bars x = np.arange(len(cats)) plt.bar(x - 0.2, vals1, 0.4, label='G1') plt.bar(x + 0.2, vals2, 0.4, label='G2') plt.xticks(x, cats)
📉 8. Histograms
data = np.random.randn(1000) # normal distribution plt.hist(data, bins=30, color='steelblue', edgecolor='black', alpha=0.7) # Density (normalized) plt.hist(data, bins=30, density=True) # Stacked / multiple plt.hist([data1, data2], bins=20, label=['A', 'B'], color=['blue', 'orange'], alpha=0.7) plt.legend() plt.show()
🔲 9. Subplots
# Create 2×2 grid of subplots fig, axes = plt.subplots(2, 2, figsize=(12, 8)) axes[0, 0].plot(x, np.sin(x)) axes[0, 0].set_title("Sine") axes[0, 1].plot(x, np.cos(x), color='orange') axes[0, 1].set_title("Cosine") axes[1, 0].bar(cats, values) axes[1, 0].set_title("Bar") axes[1, 1].hist(data, bins=20) axes[1, 1].set_title("Histogram") plt.tight_layout() # prevent overlap plt.show()
💾 10. Saving Figures
# Save before plt.show() plt.savefig("chart.png") plt.savefig("chart.pdf") plt.savefig("chart.svg") # With options plt.savefig("chart.png", dpi=300, # resolution bbox_inches='tight', # no clipping transparent=True) # transparent bg # Using figure object fig, ax = plt.subplots() ax.plot(x, y) fig.savefig("output.png", dpi=150)
✅ Best Practices
🏷️ Label Your Axes
Always include axis labels and a title. A chart without context is unreadable.
📊 Choose the Right Chart
Use line for trends, bar for comparisons, scatter for correlations, hist for distributions.
🎨 Use Consistent Colors
Stick to a defined palette. Use tab10 or Set2 colormaps for categoricals.
🧹 Avoid Clutter
Remove chart junk — unnecessary gridlines, borders, or legends that don't add meaning.
📐 Use tight_layout()
Always call plt.tight_layout() before saving to avoid clipped labels.
📁 Save at High DPI
Use dpi=300 for print-quality exports and bbox_inches='tight'.