Adding labels to a Bokeh plot

10,450

Solution 1

You're on the right path. However, the source for LabelSet has to be a DataSource. Here is an example code.

from bokeh.plotting import show, ColumnDataSource
from bokeh.charts import Scatter
from bokeh.models import LabelSet
from pandas.core.frame import DataFrame

source = DataFrame(
    dict(
        off_rating=[66, 71, 72, 68, 58, 62],
        def_rating=[165, 189, 220, 141, 260, 174],
        names=['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan']
    )
)


scatter_plot = Scatter(
                source,
                x='off_rating',
                y='def_rating',
                title='Offensive vs. Defensive Eff',
                color='navy')

labels = LabelSet(
            x='off_rating',
            y='def_rating',
            text='names',
            level='glyph',
            x_offset=5, 
            y_offset=5, 
            source=ColumnDataSource(source), 
            render_mode='canvas')

scatter_plot.add_layout(labels)

show(scatter_plot)

Solution 2

Solution by @Oluwafem is not working, as bokeh.charts is deprecated. Here is an updated solution

from bokeh.plotting import figure, output_file, show,ColumnDataSource
from bokeh.models import  ColumnDataSource,Range1d, LabelSet, Label

from pandas.core.frame import DataFrame
source = DataFrame(
    dict(
        off_rating=[66, 71, 72, 68, 58, 62],
        def_rating=[165, 189, 220, 141, 260, 174],
        names=['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan']
    )
)
p = figure(plot_width=600, plot_height=450, title = "'Offensive vs. Defensive Eff'")
p.circle('off_rating','def_rating',source=source,fill_alpha=0.6,size=10, )
p.xaxis.axis_label = 'off_rating'
p.yaxis.axis_label = 'def_rating'
labels = LabelSet(x='off_rating', y='def_rating', text='names',text_font_size='9pt',
              x_offset=5, y_offset=5, source=ColumnDataSource(source), render_mode='canvas')
p.add_layout(labels)
show(p)

enter image description here

Share:
10,450
jhaywoo8
Author by

jhaywoo8

Updated on June 07, 2022

Comments

  • jhaywoo8
    jhaywoo8 almost 2 years

    I have a data frame with columns with player names and their stats. I've plotting two different stats would like the player names to appear under each dot on the scatterplot.

    This is what I have so far but it's not working. For text, I assume this is the list of names I want under each point on the plot and source is where the names are coming from.

    p = Scatter(dt,x='off_rating',y='def_rating',title="Offensive vs. Defensive Eff",color="navy")
    labels = LabelSet(x='off_rating',y='def_rating',text="player_name",source=dt)
    p.add_layout(labels)