Matplotlib:使用同一图形绘制多个图形,但它们不重叠
我有一个类,我用它来绘制内容然后将它们保存到文件中。这是它的简化版本:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Test():
def __init__(self, x, y, filename):
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, y, 'D', color='red')
ax.set_xbound(-5,5)
ax.set_ybound(-5,5)
plt.savefig('%s.png' % filename)
test1 = Test(1,2, 'test1')
test2 = Test(2,4, 'test2')
这是结果:
test1
测试2
问题是 test2 图像也具有 test1 中的点。这些图表是在循环中动态生成的,因此我无法对数字进行硬编码。
我可以创建一个计数器并将其传递给类构造函数,但我想知道是否有更优雅的方法来做到这一点。我尝试删除 test1 对象,但没有执行任何操作。
I have a class which I use to plot things then save them to a file. Here's a simplified version of it:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Test():
def __init__(self, x, y, filename):
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, y, 'D', color='red')
ax.set_xbound(-5,5)
ax.set_ybound(-5,5)
plt.savefig('%s.png' % filename)
test1 = Test(1,2, 'test1')
test2 = Test(2,4, 'test2')
Here are the results:
test1
test2
The problem is that the test2 image also has the point from test1. The graphs are generated dynamically in a loop so I can't hardcode the figure number.
I could make a counter and pass it to the class constructor but I was wondering if there's a more elegant way to do this. I tried deleting the test1 object but that didn't do anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用图形的 clf 方法完成后清除数字。另外, pyplot.clf 将清除当前数字。
或者,如果您只想要一个新图形,请调用 pyplot.figure 没有显式的
num
参数——它会自动递增,所以你不需要保留计数器。You could use the figure's clf method to clear the figure after you're done with one. Also, pyplot.clf will clear the current figure.
Alternatively, if you just want a new figure then call pyplot.figure without an explicit
num
argument -- it will autoincrement, so you don't need to keep a counter.