Search code examples
bokeh

Changing grid position in Bokeh


I'm trying to make a table to represent the relationship between categorical values based on their count. This is my current code:

source = ColumnDataSource(df)
mapper = LinearColorMapper(palette=brewer['YlGnBu'][4], low=df['count'].min(), high=df['count'].max())
tooltips = [
    ("Resource", "@org:resoure"),
    ("Activity", "@concept:name"),
    ("Count", "@count"),
]
p = figure(plot_width=df['org:resource'].nunique()*180, plot_height=df['concept:name'].nunique()*100, title="US Unemployment 1948—2016",
           y_range=df['concept:name'].unique(), x_range=df['org:resource'].unique(),x_axis_location="above", tooltips=tooltips)

p.rect(y="concept:name", x="org:resource", width=1, height=1, source=source,
       line_color=None, fill_color=transform('count', mapper))

color_bar = ColorBar(color_mapper=mapper, location=(0, 0),
                     ticker=BasicTicker(),
                     formatter=PrintfTickFormatter(format="%d%%"))

p.add_layout(color_bar, 'right')

p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "13px"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = 0

output_notebook()
show(p)

However, this code produces a grid that does not suite categorical values. How can I shift the grid down?

current visual produced by code


Solution

  • You can achieve this using a FixedTicker.

    Here is a very basic example where p.rect() is used.

    old new
    original ticker shiftet ticker

    The code is very similar, except the ticks are shifted by 0.5 on both axis in the new version using the FixedTicker I mentioned.

    old

    from bokeh.plotting import figure, output_file, show
    
    data = [1, 5]
    plot = figure(plot_width=300, plot_height=300)
    plot.rect(x=data, y=data, width=1, height=1, color="#CAB2D6")
    
    show(plot)
    

    new

    from bokeh.plotting import figure, output_file, show
    from bokeh.models import FixedTicker
    
    data = [1, 5]
    plot = figure(plot_width=300, plot_height=300)
    plot.rect(x=data, y=data, width=1, height=1, color="#CAB2D6")
    
    _max = max(data)
    plot.xaxis.ticker = FixedTicker(ticks=[x+0.5 for x in range(_max+1)])
    plot.yaxis.ticker = FixedTicker(ticks=[x+0.5 for x in range(_max+1)])
    
    show(plot)