在Matplotlib中,如何清除轴的内容而不删除其轴标签? [英] In Matplotlib, how can I clear an axes' contents without erasing its axis labels?

查看:145
本文介绍了在Matplotlib中,如何清除轴的内容而不删除其轴标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

axes.clear()是否有替代方法,可在擦除轴内容的同时保持轴标签不变?

Is there an alternative to axes.clear() that leaves the axis labels untouched, while erasing the axes' contents?

上下文:我有一个交互式脚本,可以浏览一些流图像,对于每个图像,使用axes.quiver() 绘制它.如果我不在对axes.quiver() 的调用之间调用axes.clear(),则每个quiver() 调用只会向绘图添加更多箭头,而无需先擦除先前添加的箭头.但是,当我调用axes.clear() 时,它会核对轴标签.我可以重新设置它们,但这有点烦人.

Context: I have an interactive script that flips through some flow images, and for each image, plots it using axes.quiver(). If I don't call axes.clear() between calls to axes.quiver(), each quiver() call just adds more arrows to the plot without first erasing the previously added arrows. However, when I call axes.clear(), it nukes the axes labels. I can re-set them, but it's a bit annoying.

推荐答案

您可以使用艺术家的 remove() 从轴上移除艺术家.下面的代码显示了这样做的两个选项.

You can remove the artists from an axes using the remove() of the artists. Below is a code showing two options to do so.

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

这篇关于在Matplotlib中,如何清除轴的内容而不删除其轴标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆