matplotlib plt.show()只选择对象

Ana*_*ake 5 python matplotlib

我有几个plt.plot实例,我只想要plt.show()某些对象.这里说明一些代码:

import matplotlib.pyplot as plt

ax1 = plt.plot(range(5),range(5))
ax2 = plt.plot([x+1 for x in range(5)],[x+1 for x in range(5)])
ax3 = plt.plot([x+2 for x in range(5)],[x+2 for x in range(5)])

#plt.show([ax1,ax2])
plt.show()
Run Code Online (Sandbox Code Playgroud)

所以我希望像注释掉的语句一样,在示例图中只显示ax1和ax2.

Eri*_*got 5

您可以从当前轴的一组线中删除一些绘制的线:

axes = plt.gca()  # Get current axes
axes.lines.remove(ax2[0])  # Removes the (first and only) line created in ax2
plt.draw()  # Updates the graph (in interactive mode)
Run Code Online (Sandbox Code Playgroud)

如果你想把它放回去,你可以同样地做

axes.lines.append(ax2[0])  # Puts the line back (the drawing order is changed, here)
Run Code Online (Sandbox Code Playgroud)

如果您以后需要将它们放回原处,您也可以保存当前的图形线:

all_lines = list(axes.lines)  # Copy
# ...
axes.lines[:] = all_lines  # All lines put back
Run Code Online (Sandbox Code Playgroud)

关键是每个plot()命令都会在当前轴上添加一条线并绘制它(在交互模式下)。所以你可以删除已经绘制的线条(就像在这个答案中一样)。

正如 Yann 指出的那样,您还可以使某些线条不可见。但是,此答案中的方法可能更快,因为要绘制的线条较少(如果这很重要)。