为什么matplotlib中的图例在`savefig()`之后不能清除?

时间:2018-07-10 20:41:56

标签: python matplotlib python-3.6 legend

我正在交互使用Python 3.6。如果我将下面的代码从文本文件粘贴到Python命令行中,则它可以连续多次正常运行。但是,注释掉show()并启用pp.savefig(...)行时,每次我粘贴整个代码块时,图例都会重复出现“ abc”多次。 到底是怎么回事?有没有办法清除图例,以便每次都重新开始?

import matplotlib.pyplot as pp

pp.title("Szekeres Polynomials")
pp.legend([]) # clears the legend? no!
pp.plot([1,2,3], [8,5,4], '-', label='xxxabc' )
pp.legend(loc='best', shadow=True )
#pp.show()
pp.savefig('TMPxxx.eps', format='eps', dpi=600)

2 个答案:

答案 0 :(得分:2)

在这种情况下,您应该在保存新图形之前close绘制对象,以避免附加信息:

import matplotlib.pyplot as pp

pp.title("Szekeres Polynomials")
pp.legend([]) # clears the legend? no.
pp.plot([1,2,3], [8,5,4], '-', label='xxxabc' )
pp.legend(loc='best', shadow=True )
#pp.show()
pp.savefig('TMPxxx.eps', format='eps', dpi=600)

# Close last plot object 
plt.close()

参考文献:

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.close.html

答案 1 :(得分:1)

就像@ImportanceOfBeingErnest对您的问题的评论一样,每次您运行pp.plot()时,如果您未指定要绘制的图形,它将在同一图形上再绘制一条线。 为避免这种歧义,您可能想遵循@Lorran Sutter的建议或开始在matplotlib中使用对象,那么您的代码将变为:

fig1 = pp.figure() #Creating new figure
ax1 = fig1.add_subplot(111) #Creating axis
ax1.set_title("Szekeres Polynomials")
ax1.plot([1,2,3], [8,5,4], '-', label='xxxabc' )
ax1.legend(loc='best', shadow=True)
fig1.savefig('TMPxxx.eps', format='eps', dpi=600)

这可以确保每个新图都在新图上,而不是在前一个图上。


使用对象的好处

通过这种方式绘制图形不仅可以解决您的问题,还可以进行高级绘制并保存多个图形而不会造成混淆。

例如,绘制三个图形时,每个图形内部都包含几个子图:

fig = pp.figure() #Creating the first figure    
ax = fig.add_subplot(111)
ax.set_title("Szekeres Polynomials")
ax.plot([1,2,3], [8,5,4], '-', label='xxxabc' )
ax.legend(loc='best', shadow=True)
fig.savefig('TMPxxx.eps', format='eps', dpi=600)

fig1 = pp.figure() #Creating the second figure    
ax1 = fig1.add_subplot(121)
ax1.set_title("Szekeres Polynomials")
ax1.plot([1,2,3], [8,5,4], '-', label='xxxabc' )
ax1.legend(loc='best', shadow=True) 

ax2 = fig1.add_subplot(122)
ax2.set_title("Second Szekeres Polynomials")
ax2.plot([3,9,10], [10,15,20], '-', label='xxx' )
ax2.legend(loc='best', shadow=True)
fig1.savefig('TMPxxx2.eps', format='eps', dpi=600)

fig2 = pp.figure() #Creating the third figure    
ax21 = fig2.add_subplot(131)
ax21.set_title("hahah")
ax21.plot([1,2,3], [1,2,3], '-', label='1', c='r')
ax21.legend(loc='best', shadow=True)

ax22 = fig2.add_subplot(132)
ax22.set_title("heheh")
ax22.plot([1,2,3], [-1,-2,-3], '-', label='2', c='b')
ax22.legend(loc='best', shadow=True)

ax23 = fig2.add_subplot(133)
ax23.set_title("hohoho")
ax23.plot([1,2,3], [2**2,4**2,6**2], '-', label='3', c='g' )
ax23.legend(loc='best', shadow=True)

fig2.savefig('graph2.eps', format='eps', dpi=600)

enter image description here enter image description here enter image description here

您可以轻松调整每个子图的参数并保存三个图形,而不会造成任何混淆。