Plotting

xlwings Lite lets you create plots with the usual Python plotting libraries and bring them into Excel. Depending on where your code runs—a custom function, a script, or the notebook—the way you display a plot differs slightly. This page gives you an overview of all three.

At a glance:

Where

How the plot is shown

Libraries

Custom functions

Returned as an in-cell image into the calling cell. An over-the-cells image can be added.

Matplotlib*

Scripts

Embedded as a picture on the sheet

Matplotlib*

Notebook

Rendered inline in the output pane.

Matplotlib* and Plotly

* This includes all libraries that are built on top of Matplotlib, including pandas, Seaborn, Plotnine, etc.

Custom functions

See Plots in the custom functions tutorial.

Scripts

In a script, you have access to the Excel object model, so you can embed a plot as a picture directly onto a sheet via sheet.pictures.add():

import matplotlib.pyplot as plt
import xlwings as xw
from xlwings import script

@script
def add_plot(book: xw.Book):
    sheet = book.sheets[0]

    fig, ax = plt.subplots()
    ax.plot([1, 2, 3, 4, 5])

    sheet.pictures.add(fig, name="MyPlot", update=True, anchor=sheet["A1"])

A few things to note:

  • Use name together with update=True to replace an existing picture with the same name instead of adding a new one on every run.

  • You can fine-tune the export with export_options, which is passed on to Matplotlib’s savefig(), e.g. export_options={"dpi": 300}.

Notebook

The notebook.py tab works like a Jupyter notebook: cells are separated with # %% and their output is shown in the output pane.

Matplotlib

# %%
import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4, 5])

or, using the object-oriented interface:

# %%
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5])

Plotly

# %%
import plotly.express as px

df = px.data.iris()
px.scatter(df, x="sepal_width", y="sepal_length", color="species")

or

# %%
import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.show()