pythonformatbokehpaneltext-formatting

How do I format numeric values in a Panel widget?


Using the Python library Panel, I'm trying to format an IntSliderRange to f"{the_slider_number} kr" but the formatting argument in that class is not doing anything with the python text formatting tricks I am familiar with: 'kr', '{} kr', '{0} kr', etc.

Running help(pn.widgets.IntRangeSlider) tells me that I have to provide "A format string or bokeh TickFormatter" but I can't seem to find any relevant search results based on that.

Copilot suggests '0[.]0a' as an argument which does stuff to the format, namely express the numbers in thousands (1234 -> "1.2k"), but that's not at all what I want.

Does anyone recognize this formatting system? Where can I find out how to use it?


Solution

  • The best place to start is the bokeh documentation about formatters and in particular the section about the predefiend formatters of the NumeralTickFormatter. All these examples can you use and pass to your slider.

    from bokeh.plotting import show, output_notebook
    from bokeh.models import Slider
    output_notebook()
    
    slider = Slider(
        start=0,
        end=10,
        value=2,
        step=0.1,
        format ='$0,0.00'
    )
    show(slider)
    

    Slider with dollor sing in formatter

    In addition you can pass any instance of a formatter to the format. For example if you want a sign, there is no existing string notation. But you could make use of the PrintfTickFormatter to modifiy the string.

    from bokeh.plotting import show, output_notebook
    from bokeh.models import Slider, PrintfTickFormatter
    output_notebook()
    slider = Slider(
        start=0,
        end=10,
        value=2,
        step=0.1,
        format = PrintfTickFormatter(format='€%.2f')
    )
    show(slider)
    

    Slider with euro sing in formatter