How to set / replace text in bqplot label?

283 views Asked by At

Original question:

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

I have solved that problem and show my answer below.

New question:

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?

I want to replace the label text with something new. In particular, I want the label to reflect a changing slider value.

After being confused for some time, this is what I have found:

  • To create a label, the text (and x and y position too) have to be given as a list: label(text=['my label']). You can't just pass the string: label(text='my label').

  • To update this text, you must replace the whole list: my_label.text = ['new label']. You cannot just assign the element: my_label.text[0] = 'new label'.

Here is code that demonstrates the behavior.

# 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)
0

There are 0 answers