【发布时间】:2022-01-27 03:36:51
【问题描述】:
我编写了一个函数来按特定顺序显示条形图。该函数将需求作为参数。
代码如下:
def display_plot(demand = 0):
plt.figure(figsize = (20, 10))
x = ["A","B","C","D","E","F","G","H"]
y = [-25, -10, 5, 10, 30, 40, 50, 60]
w = [300, 200, 205, 400, 200, 400, 540, 630]
w_cumulative = [300, 500, 705, 1105, 1305, 1705, 2245, 2875]
colors = ["yellow","limegreen","green","blue","red","brown","grey","black"]
xpos = [150.0, 400.0, 602.5, 905.0, 1205.0, 1505.0, 1975.0, 2560.0]
fig = plt.bar(xpos,
height = y,
width = w,
color = colors,
alpha = 0.5,
)
#For loop to get the cutoff value
for index in range(len(w_cumulative)):
if w_cumulative[index] < demand:
pass
else:
cut_off_index = index
print (cut_off_index)
break
plt.hlines(y = y[cut_off_index],
xmin = 0,
xmax = demand,
color = "red",
linestyle = "dashed")
plt.xlim((0, w_cumulative[-1]))
plt.vlines(x = demand,
ymin = 0,
ymax = y[cut_off_index])
plt.text(x = demand - 5,
y = y[cut_off_index]+5,
s = str(y[cut_off_index]))
plt.show()
我尝试与此函数创建的绘图进行交互。这里用户定义的特征是demand。当我改变需求时,hlines 和 vlines 也会相应改变。以及显示每个条形高度的文本。
使用
from ipywidgets import *
interact(display_plot, demand = (0, sum(w), 10))
当我单击滑块上的某个点来更改值时,它是比较好的。但是,当我拖动滑块时,绘图会闪烁很多。这很烦人。我认为这是因为我在 display_plot 函数中使用了 for 循环,该循环计算 cut_off_index 的瞬时值,同时通过拖动滑块更改 demand。
我尝试通过从from IPython.display import clear_output 调用在display_plot() 函数中添加clear_output(wait=True)。我还尝试在函数中添加time.sleep(1)。但是,在拖动滑块时,绘图仍然闪烁很多。绘图的高度始终是恒定的。但是当我交互时,只有里面的内容需要更新。有什么办法可以避免这种情况下的剧情闪退?
【问题讨论】:
标签: python python-3.x user-interface jupyter-notebook ipywidgets