Plotnine is a Python implementation of a grammar of graphics, based on and compatible with the syntax of R’s ggplot2.
To plot a plotnine chart in Excel you first create the ggplot object in exactly the same way
you would in any Python script using plotnine, and then use PyXLL’s plot function to
show it in the Excel workbook.
from pyxll import xl_func, plot
from plotnine import ggplot, aes, geom_point
from plotnine.data import mtcars
@xl_func
def plotnine_plot():
# Create the ggplot object
chart = (
ggplot(mtcars, aes(x="wt", y="mpg", color="factor(cyl)"))
+ geom_point()
)
# 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.
Unlike plotly, bokeh and altair, plotnine charts are always displayed in Excel as static images and not as interactive web controls, since plotnine has no interactive HTML output of its own.
If you set an explicit figure size using plotnine’s theme(figure_size=...) that size is used
as the initial size of the image in Excel. Otherwise the default image size is used, in the same
way as for a matplotlib figure.
from pyxll import xl_func, plot
from plotnine import ggplot, aes, geom_point, theme
@xl_func
def plotnine_plot():
chart = (
ggplot(mtcars, aes(x="wt", y="mpg", color="factor(cyl)"))
+ geom_point()
+ theme(figure_size=(8, 6))
)
plot(chart)
When exporting as an image an SVG image may be used. If your version of Excel does not support SVG
images (Excel 2016 or earlier), or you are having problems with the SVG image not displaying
correctly, you can tell PyXLL to use the PNG format instead by passing allow_svg=False to
plot.
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.
Support for plotnine charts was added in PyXLL 5.13.