【问题标题】:How can I remove points from a matplotlib plot before plotting a new one?如何在绘制新点之前从 matplotlib 图中删除点?
【发布时间】:2014-07-23 21:21:20
【问题描述】:

我正在尝试绘制一个位置由滑块控制的点。但是,每次移动滑块时都会绘制一个新点,而不会删除旧点。如何在绘制新点之前删除旧点?

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider

def on_change(val):
    point=ax.scatter(x[int(val)/1],y[int(val)/1],z[int(val)/1])

x=[0,0.5,1]
y=[0,0.5,1]
z=[0,0.5,1]
p=0
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot([0,0,0,0,0,1,1,0,0,1,1,1,1,1,1,0],[0,1,1,0,0,0,0,0,1,1,0,0,1,1,1,1],[0,0,1,1,0,0,1,1,1,1,1,0,0,1,0,0],c='black',zorder=10)
point=ax.scatter(x[p],y[p],z[p],zorder=0)
ax.set_xlabel('Width')
ax.set_ylabel('Depth')
ax.set_zlabel('Height')
slider_ax = plt.axes([0.15, 0.05, 0.7, 0.02])
slider = Slider(slider_ax, "min", 0, 2, valinit=1, color='blue')
slider.on_changed(on_change)
pyplot.show()

【问题讨论】:

  • 您缺少一些导入。请添加它们。是 plt pyplot 吗?如果是这样,那你为什么还要使用 pyplot?通常人们从 matplotlib import pyplot as plt 但我不确定你的约定是什么。
  • 我修复了导入,但没有解决问题。
  • 但是现在其他人可以运行你的代码了。问题是您正在绘制子图;通常,当您调用 plt.scatter 时,它会返回绘制点的句柄。即 points = plt.scatter(whatever) 在这里,您调用的是 scatter,但由于它是一个子图,因此您在轴上进行散射。并且轴返回的句柄没有remove方法。您可以尝试重新绘制整个内容。但这并不理想。我在看看我能不能搞清楚。
  • @Daryl 不确定您在说什么。 scatter 返回的PathCollection 肯定有remove 方法。
  • 嗯,我想 remove 方法在我尝试时对我没有任何帮助 - 无论如何,HYRY 可能已经解决了你的问题。

标签: python matplotlib plot slider


【解决方案1】:

您可以更改point的属性:

def on_change(val):
    point.set_offsets([x[int(val) / 1], y[int(val) / 1]])
    point.set_3d_properties([z[int(val) / 1]], "z")
    fig.canvas.draw()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2019-08-03
    • 2014-09-21
    相关资源
    最近更新 更多