logo

Saving axes and plots for later on the fly modification

Introduction

A feature useful feature present in Matlab is the ability to save the state of a figure for later modifications, i.e. changing styles between paper and presentations. Matplotlib can utilize the same capabilities by using the serializing and deserialzing pickle module. Serializing data is a way to preserve the state of arrays or objects for later use, and it works with Matplotlib since v1.2.

Here is an example in the ipython shell:

import numpy as np
import matplotlib.pyplot as plt
import pickle

x = np.linspace(-np.pi, np.pi)
y = np.cos(x)
fig, ax = plt.subplots(1, 1)
ax.plot(x, y, label='cos(x)')
ax.set_xlabel('Time (s)')

# Pickle a tuple of figure and axes to a file
pickle.dump((fig, ax), open('myplot.pickle', 'wb'))

You can now close the session and work on it later. For example, I forgot to add a label to the y-axis. Opening a new ipython shell, I can do the following:

import matplotlib.pyplot as plt
import pickle

# Unpickle your figure and axes
fig, ax = pickle.load(open('myplot.pickle', 'rb'))
ax.set_ylabel('Voltage (mV)')
ax.minorticks_on()
ax.legend()

plt.savefig('myplot.png')

# Update the state by pickling the data again
pickle.dump((fig, ax), open('myplot.pickle', 'wb')

The ‘wb’ and ‘rb’ means to write binary and to read binary respectively.

NB Remember to only unpickle from trusted sources, because rogue code could be embedded in a pickled file.

© 2017–2022 David Kalliecharan