Kevin
Kevin

Reputation: 51

Is python matplotlib.pyplot globally scoped?

Most of the times, we import matplotlib.pyplot as follows, and use plt to plot graphs/diagrams.

import matplotlib.pyplot as plt

x = ...
plt.plot(x, sin(x))
...
plt.savefig('/path/to/sin_x.png')

plt.plot(x, cos(x))
...
plt.savefig('/path/to/cos_x.png')

My question is how to use plt as a local variable, like this?

plt1 = get_plot()
plt1.title('y = sin(x)')
...
plt1.plot(x, sin(x))
plt1.savefig('/path/to/sin_x.png')

plt2 = get_plot()
plt2.title('y = cos(x)')
...
plt2.plot(x, cos(x))
plt2.savefig('/path/to/cos_x.png')

plt1 == plt2 # false

Or, customizations on the first figure won't affect the second one without explicitly calling plt.clf()?

Upvotes: 1

Views: 638

Answers (1)

tmdavison
tmdavison

Reputation: 69116

This is a good example of the benefits of the matplotlib object-oriented interface over the "state-machine" interface (see, for example, here and here).

The differences:

State-machine

import matplotlib.pyplot as plt
plt.plot(x, sin(x))
plt.savefig('plot.png')

OO interface

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, sin(x)
fig.savefig('plot.png')

When using the OO interface, you can create as many figure and Axes instances, and refer back to them without interfering with other instances.

For example:

import matplotlib.pyplot as plt

# Create first figure instance
fig1 = plt.figure()
# Add an Axes instance to the figure
ax1 = fig1.add_subplot(111)
# Set the title
ax1.set_title('y = sin(x)')
# Plot your data
ax1.plot(x, sin(x))
# Save this figure
fig1.savefig('/path/to/sin_x.png')

# Now create a second figure and axes. Here I use an altenative method, 
# plt.subplots(1), to show how to create the figure and axes in one step.
fig2, ax2 = plt.subplots(1)
ax2.set_title('y = cos(x)')
ax2.plot(x, cos(x))
fig2.savefig('/path/to/cos_x.png')

# If you want to, you could modify `ax1` or `fig1` here, without affecting `fig2` and `ax2`

Upvotes: 2

Related Questions