matplotlib: Figure & Axes
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4))
fig, axes = plt.subplots(2, 2) # grid
plt.style.use("seaborn-v0_8-darkgrid")
fig.tight_layout()
fig.suptitle("Title")
fig.savefig("out.png", dpi=150, bbox_inches="tight")
plt.show()
matplotlib: Plot Types
ax.plot(x, y, color="teal", ls="--", lw=2, marker="o")
ax.scatter(x, y, c=z, cmap="viridis", alpha=0.7)
ax.bar(cats, vals); ax.barh(cats, vals)
ax.hist(data, bins=20, edgecolor="white")
ax.boxplot(data)
ax.fill_between(x, lo, hi, alpha=0.2)
ax.pie(vals, labels=cats) # use sparingly
matplotlib: Labels & Style
ax.set_title("t")
ax.set_xlabel("x"); ax.set_ylabel("y")
ax.set_xlim(0, 10); ax.set_ylim(-1, 1)
ax.set_xticks([0, 5, 10])
ax.legend(loc="upper right")
ax.grid(True, alpha=0.3)
ax.annotate("pt", xy=(1, 1), xytext=(2, 2),
arrowprops=dict(arrowstyle="->"))
ax.axhline(0); ax.axvline(5)
seaborn
Distributions
import seaborn as sns
sns.histplot(df, x="v", hue="g", kde=True)
sns.kdeplot(df, x="v")
sns.boxplot(df, x="g", y="v")
sns.violinplot(df, x="g", y="v")
sns.countplot(df, x="g")
Relationships
sns.scatterplot(df, x="a", y="b", hue="g")
sns.lineplot(df, x="t", y="v", hue="g")
sns.regplot(df, x="a", y="b") # + fit line
sns.pairplot(df, hue="g", diag_kind="kde")
sns.heatmap(df.corr(), annot=True, cmap="coolwarm",
vmin=-1, vmax=1, fmt=".2f")
plotly express
import plotly.express as px
px.scatter(df, x="a", y="b", color="g",
size="s", hover_name="name")
px.line(df, x="t", y="v", color="g")
px.bar(df, x="g", y="v")
px.histogram(df, x="v", nbins=20)
px.box(df, x="g", y="v")
px.imshow(df.corr()) # heatmap
fig.show(); fig.write_html("out.html")
Chart Picker
| Goal |
Chart |
| Trend over time | Line |
| 2 numeric relationship | Scatter |
| Compare categories | Bar |
| Distribution | Histogram / KDE |
| Spread & outliers | Box / Violin |
| Correlation | Heatmap |
| Multi-var overview | Pairplot |
Common Kwargs
| Kwarg |
Controls |
color / c | Line/marker color |
alpha | Transparency 0-1 |
cmap | Colormap |
hue | seaborn color group |
bins | Histogram buckets |
figsize | Figure size (in) |