Search code examples
pythonbokeh

How to add data labels to a bar chart in Bokeh?


In the Bokeh guide there are examples of various bar charts that can be created. http://docs.bokeh.org/en/0.10.0/docs/user_guide/charts.html#id4

This code will create one:

from bokeh.charts import Bar, output_file, show
from bokeh.sampledata.autompg import autompg as df

p = Bar(df, 'cyl', values='mpg', title="Total MPG by CYL")

output_file("bar.html")

show(p)

My question is if it's possible to add data labels to each individual bar of the chart? I searched online but could not find a clear answer.


Solution

  • Use Labelset

    Use Labelset to create a label over each individual bar

    In my example I'm using vbar with the plotting interface, it is a little bit more low level then the Charts interface, but there might be a way to add it into the Bar chart.

    from bokeh.palettes import PuBu
    from bokeh.io import show, output_notebook
    from bokeh.models import ColumnDataSource, ranges, LabelSet
    from bokeh.plotting import figure
    output_notebook(hide_banner=True) # hide Bokeh banner
    
    source = ColumnDataSource(dict(x=['Áætlaðir','Unnir'],y=[576,608]))
    
    x_label = ""
    y_label = "Tímar (klst)"
    title = "Tímar; núllti til þriðji sprettur."
    plot = figure(width=600, height=300, tools="save",
            x_axis_label = x_label,
            y_axis_label = y_label,
            title=title,
            x_minor_ticks=2,
            x_range = source.data["x"],
            y_range= ranges.Range1d(start=0,end=700))
    
    
    labels = LabelSet(x='x', y='y', text='y', level='glyph',
                      text_align='center', y_offset=5, source=source)
    
    plot.vbar(source=source,x='x',top='y',bottom=0,width=0.3,color=PuBu[7][2])
    
    plot.add_layout(labels)
    show(plot)
    

    Bar chart with labels on top of each bar

    You can find more about labelset here: Bokeh annotations