在不清除滑块的情况下清除 Matplotlib 图

Clearing the Matplotlib plot without clearing slider

我目前正在创建一个需要更新 matplotlib 图形的应用程序。我被困在下面的步骤。
我在同一个图中有一个散点图和滑块。更改滑块值后,我需要在不清除滑块的情况下清除散点图。以下是我实现的代码,但它没有清除情节。 .clf() 函数删除滑块和散点图。有没有一种方法可以只删除绘图而不影响滑块?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider


X1=np.arange(10)
Y1=np.arange(10)
Z1=np.arange(10)
fig,ax=plt.subplots()
ax=plt.scatter(X1,Y1,Z1)

axSlider1=plt.axes([0.3,0.9,0.3,0.05])
Slder2=Slider(ax=axSlider1,label='Slider',valmin=1,valmax=4,valinit=2)

plt.show()

# Function to clear the scatter plot without effecting slider.
def val_update(val):
    plt.cla()

Slder2.on_changed(val_update)

fig,ax=plt.subplots()

将 Axes 对象分配给 ax - 然后

ax=plt.scatter(X1,Y1,Z1)

将 PathCollection 对象分配给 ax。所以 val_update 被绑在错误的事情上。

这似乎解决了您提出的问题。

X1=np.arange(10)
Y1=np.arange(10)
Z1=np.arange(10)
fig,ax=plt.subplots()
path=plt.scatter(X1,Y1,Z1)

axSlider1=plt.axes([0.3,0.9,0.3,0.05])
Slder2=Slider(ax=axSlider1,label='Slider',valmin=1,valmax=4,valinit=2)


# Function to clear the scatter plot without effecting slider.
def val_update(val):
    print(val)
    ax.clear()

Slder2.on_changed(val_update)

plt.show()

Matplotlib Gallery is a good resource you can browse through it looking for features you want and see how they were made. - Like this slider demo

如果您认为您将来会使用 matplotlib,我建议您按自己的方式完成介绍 tutorials 和至少艺术家教程