2017-03-28 186 views
2

是否有替代axes.clear()可以在保持軸標籤不變的同時擦除軸的內容?在Matplotlib中,如何清除軸的內容而不擦除其軸標籤?

語境: 我通過一些流動圖像翻轉的交互式腳本,併爲每個圖像,使用axes.quiver繪製它()。如果我在調用axes.quiver()之前不調用axes.clear(),則每次顫動()調用都會在未先刪除先前添加的箭頭的情況下向該圖添加更多箭頭。但是,當我調用axes.clear()時,它會打印軸標籤。我可以重新設定它們,但這有點煩人。

回答

1

您可以使用藝術家的remove()從軸上刪除藝術家。以下是顯示兩個選項的代碼。

import matplotlib.pyplot as plt 
import numpy as np 

X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2)) 
U = np.cos(X) 
V = np.sin(Y) 

plt.figure() 
plt.title('Arrows scale with plot width, not view') 
plt.xlabel('xlabel') 
plt.xlabel('ylabel') 

Q = plt.quiver(X, Y, U, V, units='width') 
l, = plt.plot(X[0,:], U[4,:]+2) 

# option 1, remove single artists 
#Q.remove() 
#l.remove() 

# option 2, remove all lines and collections 
for artist in plt.gca().lines + plt.gca().collections: 
    artist.remove() 

plt.show()