Search code examples
pythonbokeh

Inserting newlines in bokeh Tick Labels


I want to create tick-labels in Bokeh that are formatted over multiple lines. Formatting in this way in regular Python is trivial, eg

'{} \n{}'.format('Category', 'Percentage')

will print

Percentage

In my code, I'm doing this to create my plot data:

ds = OrderedDict(sorted(subdict.items(), key=lambda v: v[1], reverse=True))
ks = [i+', {:}% '.format(str(round(j/sum(ds.values())*100, None))) for i, j in ds.items()]
data = {'kz': ks, 'vals':list(ds.values())}
source = ColumnDataSource(data=data)

If I insert a newline into the format() statement in the above code (eg ', \n {:}%'), bokeh ignores it.

bokeh.models.PrintfTickFormatter doesn't seem to offer a newline argument,

and

bokeh.models.CategoricalTickFormatter literally does nothing (the method is 'pass')

Tucked away in the bokeh documentation

https://docs.bokeh.org/en/latest/docs/reference/models/formatters.html

for DatetimeTickFormatter is the statement:

%n A newline character. Bokeh text does not currently support newline characters.

I can only assume that this applies to all and any text in bokeh.

Can anyone confirm, or correct, or offer a workaround?

nb In my use case, the chart is only ever exported as a png.


Solution

  • As of Bokeh 2.3 multi-line tick labels are possible only for categorical factors:

    from bokeh.plotting import figure, show
    
    factors = [
        "a very long label \n that needs a break",
        "a short label",
    ]
    
    x = [50, 40]
    
    p = figure(y_range=factors)
    p.circle(x, factors, size=25, fill_color="orange", line_color="green", line_width=3)
    
    show(p)
    

    enter image description here