Matplotlib Cheat Sheet
Free Matplotlib cheat sheet: the most-used Matplotlib syntax and methods at a glance — searchable and beginner-friendly.
Basics
| Concept | Syntax | Example |
|---|---|---|
| Import pyplot The universal alias — every snippet assumes plt. | import matplotlib.pyplot as plt | import matplotlib.pyplot as plt |
| Line plot The workhorse — connects points with a line. | plt.plot(x, y) | plt.plot([1, 2, 3], [4, 5, 6]) |
| Show the figure Renders the plot window. Call it last. | plt.show() | plt.show() |
| Create a figure Set the canvas size in inches before plotting. | plt.figure(figsize=(w, h)) | plt.figure(figsize=(8, 5)) |
| Clear / close Free memory when generating many plots in a loop. | plt.clf() / plt.close() | plt.close() |
Plot Types
| Concept | Syntax | Example |
|---|---|---|
| Scatter Points with no connecting line — show correlation. | plt.scatter(x, y) | plt.scatter(heights, weights) |
| Bar chart plt.barh() for horizontal bars. | plt.bar(x, height) | plt.bar(["A", "B", "C"], [10, 20, 15]) |
| Histogram Shows the distribution of a single variable. | plt.hist(data, bins=n) | plt.hist(ages, bins=20) |
| Pie chart Add autopct="%1.1f%%" to show percentages. | plt.pie(sizes, labels=...) | plt.pie([30, 70], labels=["No", "Yes"]) |
| Box plot Visualizes median, quartiles, and outliers. | plt.boxplot(data) | plt.boxplot([group1, group2]) |
Labels & Legends
| Concept | Syntax | Example |
|---|---|---|
| Axis labels Always label your axes. | plt.xlabel() / plt.ylabel() | plt.xlabel("Year"); plt.ylabel("Sales") |
| Title A descriptive heading above the plot. | plt.title("text") | plt.title("Monthly Sales") |
| Legend Reads the label= you set on each plot call. | plt.legend() | plt.plot(x, y, label="2025"); plt.legend() |
| Axis limits Manually set the visible range of each axis. | plt.xlim() / plt.ylim() | plt.ylim(0, 100) |
| Ticks Add rotation=45 to angle long labels. | plt.xticks(positions, labels) | plt.xticks([0, 1, 2], ["Jan", "Feb", "Mar"]) |
| Text annotation Point at and label a specific data point. | plt.annotate(text, xy=(x, y)) | plt.annotate("peak", xy=(3, 9)) |
Styling
| Concept | Syntax | Example |
|---|---|---|
| Color & line style Linestyles: '-', '--', '-.', ':'. | plt.plot(x, y, color=, linestyle=) | plt.plot(x, y, color="red", linestyle="--") |
| Markers Markers: 'o', 's', '^', '*', 'x'. | plt.plot(x, y, marker=) | plt.plot(x, y, marker="o") |
| Format string shortcut Combine color+marker+linestyle in one string. | plt.plot(x, y, "fmt") | plt.plot(x, y, "ro--") # red circles, dashed |
| Line width / alpha alpha controls transparency from 0 to 1. | linewidth=, alpha= | plt.plot(x, y, linewidth=2, alpha=0.6) |
| Grid Adds reference gridlines behind the data. | plt.grid(True) | plt.grid(True, linestyle=":") |
| Built-in style Try 'seaborn-v0_8', 'fivethirtyeight', 'dark_background'. | plt.style.use("name") | plt.style.use("ggplot") |
Subplots
| Concept | Syntax | Example |
|---|---|---|
| Figure + axes grid The recommended object-oriented entry point. | fig, ax = plt.subplots(rows, cols) | fig, ax = plt.subplots(2, 2, figsize=(10, 8)) |
| Plot on an axis Each Axes object has its own plot/set methods. | ax.plot(x, y) | ax[0, 0].plot(x, y) |
| Set labels (OO style) On Axes use set_ prefixes instead of plt. functions. | ax.set_xlabel() / ax.set_title() | ax.set_title("Panel A") |
| Single subplot Index is 1-based and counts left-to-right, top-to-bottom. | plt.subplot(rows, cols, index) | plt.subplot(1, 2, 1) |
| Tidy spacing Prevents overlapping labels between subplots. | plt.tight_layout() | plt.tight_layout() |
Saving
| Concept | Syntax | Example |
|---|---|---|
| Save to file Format is inferred from the extension (.png, .pdf, .svg). | plt.savefig("name.png") | plt.savefig("chart.png") |
| High resolution 300 dpi is print quality. | plt.savefig(..., dpi=n) | plt.savefig("chart.png", dpi=300) |
| Trim whitespace Crops empty margins around the figure. | bbox_inches="tight" | plt.savefig("chart.png", bbox_inches="tight") |
| Transparent background Useful for overlaying on slides or web pages. | transparent=True | plt.savefig("chart.png", transparent=True) |
| Save before show plt.show() can clear the figure, so save first. | savefig() then show() | plt.savefig("out.png"); plt.show() |