如何删除我用滑块小部件添加的axhline



我从SO中提取了下面的代码,并对其进行了修改,使其更接近我所需要的。基本上,我希望用户移动滑块来更改轴线的位置,然后将用于进行计算。我的问题是,应该删除上一个axhline的行没有删除它,它破坏了我的功能,并且不会在滑块更改时创建新行。我的remove((调用有什么问题?当函数终止时,对axhline的引用是否丢失?我试着把它推向全球,但无济于事。

# Import libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
%matplotlib notebook
# Create a subplot
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.35)
r = 0.6
g = 0.2
b = 0.5
# Create and plot a bar chart
year = [2002, 2004, 2006, 2008, 2010]
production = [25, 15, 35, 30, 10]
plt.bar(year, production, color=(r, g, b))
targ_line = plt.axhline(y=20, xmin=-.1, clip_on=False, zorder=1, color='#e82713')
# Create 3 axes for 3 sliders red,green and blue
target = plt.axes([0.25, 0.2, 0.65, 0.03])

# Create a slider from 0.0 to 35.0 in axes target
# with 20.0 as initial value.
red = Slider(target, 'Target', 0.0, 35.0, 20)

# Create fuction to be called when slider value is changed
# This is the part I am having trouble with.  I want to remove the previous line
# so that there will only be one axhline present
def update(val):  
#targ_line.remove()   # uncommenting this line doesn't remove the line and prevents the remainder of the code in this function from running.
Y = red.val
targ_line = ax.axhline(y=Y, color = 'black')
ax.bar(year, production, color=(r, g, b),
edgecolor="black")
# Call update function when slider value is changed
red.on_changed(update)

# Create axes for reset button and create button
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color='gold',
hovercolor='skyblue')
# Create a function resetSlider to set slider to
# initial values when Reset button is clicked
def resetSlider(event):
red.reset()

# Call resetSlider function when clicked on reset button
button.on_clicked(resetSlider)
# Display graph
plt.show()

您可以尝试更新axhline,而不是重新创建它。例如:

def update(val):  
#Y = red.val
#targ_line = ax.axhline(y=Y, color = 'black')
targ_line.set_ydata(y=red.val)
targ_line.set_color('black')
ax.bar(year, production, color=(r, g, b), edgecolor="black")

最新更新