Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
As Seaborn builds on matplotlib it works perfectly with PyXLL’s plot
function.
All Seaborn plot functions use matplotlib.pyplot
to plot to the current pyplot
figure. This
can then be displayed in Excel using plot
. When passed no arguments, plot
plots
the current matplotlib.pyplot
figure and closes it.
Plots created using Seaborn are displayed in Excel as images and are not interactive controls.
from pyxll import plot, xl_func
import seaborn as sns
@xl_func
def sns_plot():
# Load a dataset to plot
penguins = sns.load_dataset("penguins")
# Plot a histogram, plotted to the current matplotlib.pyplot figure
sns.histplot(data=penguins, x="flipper_length_mm", hue="species", multiple="stack")
# Show the current matplotlib.pyplot figure using pyxll.plot
plot()
As with the previous matplotlib examples, when this function is called from Excel the plot is shown below the calling cell.
The Seaborn plotting functions also optionally take matplotlib.Axes
objects. This can be used to plot to a
specific Axes object instead of to the current matplotlib.pyplot
figure. For example, for doing subplots
or if you need more control over the matplotlib.Figure
being used.
from pyxll import plot, xl_func
import matplotlib.pyplot as plt
import seaborn as sns
@xl_func
def sns_plot():
# Load a dataset to plot
penguins = sns.load_dataset("penguins")
# Create the matplotlib Figure and Axes objects
fig, ax = plt.subplots()
# Plot a histogram to the Axes we just created
sns.histplot(data=penguins, x="flipper_length_mm", hue="species", multiple="stack", ax=ax)
# Show the matplotlib Figure created above
plot(fig)
Tip
Whenever you change an input argument to your plotting function, the chart will be redrawn.
You can use this to create interactive dashboards where the Excel user can control the inputs to the plot and see it redraw automatically.