如何设置/替换bqplot标签中的文本?

2024-06-25 23:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

原始问题:

How do you set the text in a bqplot label using a slider?

我已经解决了这个问题,并在下面给出了我的答案

新问题:

Why is this the behavior? Doesn't it seem crazy for bqplot to expose the text as a list and then not allow item assignment?

我想用新的内容替换标签文本。 特别是,我希望标签反映一个不断变化的滑块值

经过一段时间的困惑,我发现:

  • 要创建标签,文本(以及x和y位置)必须作为列表给出: label(text=['my label'])。 您不能只传递字符串: label(text='my label')

  • 要更新此文本,必须替换整个列表: my_label.text = ['new label']。 您不能只分配元素: my_label.text[0] = 'new label'

下面是演示该行为的代码

# Imports
import numpy as np
from bqplot import pyplot as plt
from ipywidgets import IntSlider, FloatSlider, Layout
from IPython.display import display

# Make plot and label
xs = np.linspace(0, 10, 100)
ys = np.sin(xs)

layout=Layout(width='40%', height='300px')

fig = plt.figure(layout=layout)
line = plt.plot(xs, ys)

value = 123.45678
lab = plt.label(text=['{:3.3f}'.format(value)], x=[5], y=[0.2], colors=['Red'], align='middle')

# Create and link sliders
good_slider = FloatSlider(description='good')#, min=0, max=100, step=0.001)
bad_slider = FloatSlider(description='bad')#, min=0, max=100, step=0.001)

def good_update_label(change):
    lab.text = ['{:3.3f}'.format(change['new'])]

def bad_update_label(change):
    lab.text[0] = '{:3.3f}'.format(change['new'])
    
good_slider.observe(good_update_label, 'value')
bad_slider.observe(bad_update_label, 'value')

# See what happens!
display(good_slider, bad_slider, fig)

Tags: thetextimportnewvaluemyasupdate