gk_stuart gk_stuart - 6 months ago 95
Python Question

Formatting log axis labels with proper superscripts in Bokeh

This is, admittedly, a minor annoyance. When using log scale axes, Bokeh formats the tick labels as "10^1" instead of "101"

enter image description here

Is there any way I can modify this so it uses the superscript?

Alternately, I would like to label with JUST the exponent. Either way looks much nicer than how it is now.

Answer

As of Bokeh 0.11.1 there is no way to have the actual superscript. Support for LaTeX labels is a long-standing feature request, but some recent other work may have helped pave the way for finally adding it in the near future.


In the mean time, you could create your own custom TickFormatter. This is a fairly advanced technique, and also fairly new. We are still working out documentation for this particular topic (there should be quite alo more guidance available on the next release). But here is a complete example to just print the exponents:

from bokeh.plotting import figure, output_file, show from bokeh.models.formatters import TickFormatter

x = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
y = [10**xx for xx in x]

output_file("log.html")

class MyTickFormatter(TickFormatter):
    __implementation__ = """
        _ = require "underscore"
        Model = require "model"

        class MyTickFormatter extends Model
          type: 'MyTickFormatter'

          doFormat: (ticks) ->
            return ("#{ Math.log10(tick) }" for tick in ticks)

        module.exports =
          Model: MyTickFormatter
    """

# create a new plot with a log axis type
p = figure(plot_width=400, plot_height=400,
           y_axis_type="log", y_range=(10**-1, 10**4))

p.line(x, y, line_width=2)
p.circle(x, y, fill_color="white", size=8)

# use the custom TickFormatter
p.yaxis[0].formatter = MyTickFormatter()


show(p)

With the result:

enter image description here