HomeCourseModule 08 › Charts in =PY() with matplotlib and seaborn

Charts in =PY() with matplotlib and seaborn

Module 08 · Python inside Excel — =PY()8 min readIntermediate

What you'll learn

  • Return a matplotlib chart from =PY()
  • Customise the chart's title, labels, and size
  • Use seaborn for prettier defaults

The simplest chart cell

=PY(
import matplotlib.pyplot as plt
df = xl("A1:D11", headers=True)
df.groupby("Region")["Revenue"].sum().plot(kind="bar")
)

The cell returns a chart image. Click it; Excel lets you resize and reposition it.

Styling

=PY(
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
df = xl("A1:D11", headers=True)
df.groupby("Region")["Revenue"].sum().plot(kind="bar", ax=ax, color="#217346")
ax.set_title("Revenue by Region")
ax.set_ylabel("Revenue ($)")
ax.set_xlabel("")
plt.tight_layout()
)

Seaborn for nicer defaults

=PY(
import seaborn as sns
df = xl("A1:D11", headers=True)
sns.barplot(data=df, x="Region", y="Revenue", estimator="sum", errorbar=None)
)

Walkthrough: monthly trend chart

Aggregate first, plot second

=PY(
import matplotlib.pyplot as plt
df = xl("A1:D11", headers=True)
df["Month"] = pd.to_datetime(df["Date"]).dt.to_period("M").dt.to_timestamp()
monthly = df.groupby("Month")["Revenue"].sum()

fig, ax = plt.subplots(figsize=(7, 3))
monthly.plot(ax=ax, marker="o", color="#2b6cb0")
ax.set_title("Monthly Revenue")
ax.grid(alpha=0.3)
plt.tight_layout()
)
💡 Treat chart cells like images
A =PY() chart behaves like an image inside the spreadsheet — you can resize it, move it across sheets, and it'll update whenever the source data changes.

Key takeaways

  • =PY() can return matplotlib/seaborn charts directly.
  • For control: build a fig, ax and tweak labels/colours.
  • Use plt.tight_layout() to avoid clipping.

Stacked bar

Build a stacked bar chart in =PY() showing Revenue by Region, with Product as the stack. Hint: df.pivot_table(...).plot(kind="bar", stacked=True).

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.