To plot a Plotly figure in Excel you first create the figure in exactly the same way you would
in any Python script using plotly, and then use PyXLL’s plot
function to show it
in the Excel workbook.
When the figure is exported to Excel it first has to be converted to an image. This is done
by PyXLL using plotly’s write_image
method. This requires an additional package kaleido
to be installed.
To install kaleido use pip install -U kaleido
, or conda install -c plotly python-kaleido
if you are using Anaconda.
PyXLL also supports using the legacy orca package, but from plotly 4.9 onwards it is recommended that you use kaleido.
Note
If you have any problems with exporting plots as SVG images you can tell PyXLL
to use the PNG format instead by passing allow_svg=False
to plot
.
The code below shows an Excel worksheet function that generates a plotly figure displayed it in Excel.
from pyxll import xl_func, plot
import plotly.express as px
@xl_func
def plotly_plot():
# Get some sample data from plotly.express
df = px.data.gapminder()
# Create a scatter plot figure
fig = px.scatter(df.query("year==2007"),
x="gdpPercap", y="lifeExp",
size="pop", color="continent",
log_x=True, size_max=60)
# Show the figure in Excel using pyxll.plot
plot(fig)
When this function is run in Excel the plot is shown just below the calling cell. The first time you export an image from plotly it can take a few seconds.
Warning
When exporting a figure to an image plotly launches a kaleido or orca subprocess to do the export.
If you have anti-virus software installed it may warn you about this subprocess being launched.
Note
The plot that you see in Excel is exported as an image so any interactive elements will not be available.
To make a semi-interactive plot you can add arguments to your function to control how the plot is done and when those arguments are changed the plot will be redrawn.