python-3.x - 如何删除使用滑块小部件添加的 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")
推荐阅读
- python - 当任何文件发生更改时,在 Docker 容器中重新启动 Python 脚本
- node.js - 无法在 win10 ubuntu 子系统上运行电子
- r - 错误:采用变量子集的索引超出范围
- javascript - 如何取消此 axios 请求
- javascript - javascript - 从 ajax 调用加载 html 内容
- python - 在 python 上加入字符串
- amazon-dynamodb - dynamodb UpdateItem 使用 API Gateway 作为代理,错误
- javascript - 迷宫生成完成后在 HTML Canvas 中加载图像
- python - 如何防止 PyQt 应用程序在退出时清除剪贴板?
- python-3.x - 如何将 Excel 上的不同数据集组织成相同的布局/顺序(使用 pandas)