全局范围内是python matplotlib.pyplot吗?

时间:2017-02-09 07:11:48

标签: python matplotlib

大多数情况下,我们按如下方式导入matplotlib.pyplot,并使用plt绘制图形/图表。

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')

我的问题是如何使用plt作为局部变量,像这样?

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

或者,第一个数字的自定义不会影响第二个,而不显式调用plt.clf()?

1 个答案:

答案 0 :(得分:1)

这是matplotlib面向对象的界面优于"状态机"的一个很好的例子。界面(例如,参见herehere)。

差异:

<强>国家机

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

OO界面

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

使用OO界面时,您可以创建尽可能多的figureAxes个实例,并在不干扰其他实例的情况下返回它们。

例如:

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`