Search code examples
pythonbokeh

How to make text in Bokeh tooltips wrap properly?


I have a graph, where each point is a post on Twitter. When you mouse over a point, a tooltip with a content of the post is displayed.

The problem is that when tooltip is displayed on the left, the text isn't wrapped. Instead, it's displayed in one line and the tooltip goes outside of the plot, so not the entire text is visible. When tooltip is displayed on the right, this problem doesn't occur – the text wraps properly and can be read. Is there some solution to this?

Here's a link to a screenshot showing badly displayed tooltip (on the left) and a properly displayed one (on the right): https://i.sstatic.net/r8HKL.jpg

from bokeh.plotting import figure, show, output_notebook, ColumnDataSource

source = ColumnDataSource(data=dict(
    x=df[0],
    y=df[1],
    desc=post_list,
))
tooltips = [
    ("text", "@desc"),
]

p = figure(tooltips=tooltips)
p.scatter(x='x', y='y', source=source)

I have tried to wrap the text myself by simply inserting newline characters (\n), but they didn't have any effect on tooltips. If someone knows, how to make them actually break lines, that would be helpful too.


Solution

  • Use custom tooltip:

    https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#custom-tooltip

    for example:

    tooltips = """
    <div style="width:200px;">
    @desc
    </div>
    """
    
    p = figure(tooltips=tooltips)