To plot a altair figure in Excel you first create the figure in exactly the same way you would
in any Python script using altair, 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 using altair_saver which also requires Selenium. Both of these must be installed before Altair can be used with PyXLL.
altair_saver can be installed using pip install altair_saver
or conda install -c conda-forge altair_saver
.
The easiest way to install Selenium is to use Anaconda and install it using either of the following commands:
conda install selenium geckodriver firefox -c conda-forge
or
conda install selenium python-chromedriver-binary -c conda-forge
If you are not using Anaconda you can use pip install selenium
but you will also need to install
a suitable web browser backend. See https://pypi.org/project/selenium/ for
additional details about how to install Selenium.
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 altair figure and displays it in Excel.
# This example requies vega_datasets.
# Install using 'pip install vega_datasets'
from vega_datasets import data
from pyxll import xl_func, plot
import altair as alt
@xl_func
def altair_plot():
# Get the sample data set
source = data.cars()
# Create the chart
chart = alt.Chart(source).mark_circle(size=60).encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin'
)
# Show it in Excel using pyxll.plot
plot(chart)
When this function is run in Excel the plot is shown just below the calling cell. The first time you export an image from altair it can take a few seconds.
Warning
When exporting a chart to an image altair launches a Selenium 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.