Matplotlib and seaborn 3 cheatsheet
Matplotlib and seaborn 3: Basics
7 common Matplotlib and seaborn 3 tasks.
Draw a line chart
Plot y against x and show the figure.
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.show()
Add a title and axis labels
Label the chart so it can be understood on its own.
plt.plot(x, np.sin(x), label="sin(x)")
plt.title("A sine wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.legend()
plt.grid(True)
Set the figure size
Create a figure with a size in inches and a resolution.
fig, ax = plt.subplots(figsize=(8, 4), dpi=120)
Save a chart to a file
Write the figure as PNG, SVG or PDF. bbox_inches="tight" trims the margins.
fig.savefig("chart.png", bbox_inches="tight")
Draw without a screen
Use the Agg backend on servers and in CI, where there is no display.
import matplotlib
matplotlib.use("Agg")