Save Arviz plots

I want to save my Arviz plots. When I do arviz.plot_trace() I get a numpy array. I can use matplotlib.pyplot.savefig(path) but that’s pretty opaque – I never know which plots are being saved.

Is there a way to simply get a figure object from the trace plot, so I can save it with figure.savefig?

3 Likes

Since arviz uses matplotlib, to save a figure, you would have to use matplotlib.pyplot.savefig(). If you use the bokeh backend`, there is another way to save a figure: https://docs.bokeh.org/en/latest/docs/user_guide/export.html

One way is to access the figure object from the axis object. ArviZ uses one figure object per plot.

axes = az.plot_trace(...)
fig = axes.ravel()[0].figure
fig.savefig(...)

For bokeh you probably want to save a layout, (each axis is it’s own bokeh figure and they are bind together with layout object)

5 Likes

For bokeh you probably want to save a layout

I’ve been struggling to figure out how to do this. Do you have an example?

Assuming you want to export them as png, it would look like:

from bokeh.io import export_png
from bokeh.layouts import gridplot

export_png(gridplot(ax.tolist()), filename="filename.png")

which should work if ax is a numpy array of length >1. For a more general thing you can try

if isinstance(ax, ndarray):
    if len(ax.shape) == 1:
        export_png(gridplot([ax.tolist()]), filename=pngfilename)
    else:
        export_png(gridplot(ax.tolist()), filename=pngfilename)
else:
    export_png(ax, filename=pngfilename)
2 Likes