yoyoyoyo123
yoyoyoyo123

Reputation: 2472

Bokeh - Format Label With Percent Sign

Using Python3 and Bokeh 0.13.0

I have a plot which is using float numbers like 22.6. These numbers are actually percents. I have labels for each point on a line but I can't figure out a way to include a % sign in the label (like 22.6%). I was able to format the axis fine, but the labels are giving me a hard time. Here is the portion of the code that defines the label.

labels = LabelSet(x='x', y='y', text='y', level='glyph',y_range_name="line",
                      x_offset=-8, y_offset=10, source=source_line, render_mode='canvas',
                      text_font_size='8pt', text_color='white', background_fill_color="gray")
p.add_layout(labels)

any help would be appreciated

Upvotes: 1

Views: 1933

Answers (1)

bigreddot
bigreddot

Reputation: 34618

You have two options:

  • You can pre-format all the data in python, store it in a new column in your ColumnDataSource, and use that to drive the label text, i.e. something like

    source.data['formatted_y'] = ["%f %" % x for x in source.data['y']]
    LabelSet(text='formatted_y', ...)
    
  • You can use a CustomJSTransform to transform the data on the JavaScript end, e.g.

    from bokeh.models import CustomJSTransform
    from bokeh.transform import transform
    
    formatter = CustomJSTransform('y',  func="", v_func="""
        out = []
        for (i=0; i < xs.length; i ++) {
           out.push(xs[i] + " %")
        }
        return out
    """)
    LabelSet(text=transform('y', formatter), ...)
    

    Note: untested, since you did not provide a complete example code it could be tested with, but should be in the ballpark

Upvotes: 3

Related Questions