Horizontal bar and line chart with multiple x-axes scales in bokeh

812 views Asked by At

I'm attempting to plot a horizontal histogram and a timeseries of the data underlying the histogram on one chart. Naturally, this requires a shared y axis and two x axes - one for the histogram frequencies and the other for the datetimes. However, I cannot seem to get the datetime axis to play nicely. It ends up incorporating the 0 values associated with the histogram, which then is converted to 1970-01-01 (not what I want).

import numpy as np
import pandas as pd
from bokeh.io import show 
from bokeh.plotting import figure
from bokeh.models import LinearAxis, DatetimeTickFormatter, Range1d

testData = pd.Series(np.random.rand(10), index=pd.date_range('2016-01-01', periods=10)
counts, bins = np.histogram(testData, bins=5)


histAndLine = figure(x_axis_type='datetime')

f = ['%Y-%m-%d']
histAndLine.xaxis.formatter = DatetimeTickFormatter(years=f, months=f, days=f)
histAndLine.extra_x_ranges = {'Counts': Range1d(0, max(counts)+1)}
histAndLine.add_layout(LinearAxis(x_range_name='Counts'), 'above')

histAndLine.line(x=testData.index, y=testData)
histAndLine.circle(x=testData.index, y=testData)

histAndLine.hbar(y=bins[:-1], height=np.diff(bins), left=0, right=counts, x_range_name='Counts')

show(histAndLine)

This should yield a bar chart over a line, with the line and bar using much of the chart space, yet my line gets squished up to the right (because 2016 dates are much much much greater than 0 = 1970.

Am I missing something here?

1

There are 1 answers

0
bigreddot On BEST ANSWER

The default DataRange1d that figures use automatically ranges over all available glyphs. If you want to exclude a subset of the glyphs, you can be explicit:

l = histAndLine.line(x=testData.index, y=testData)
c = histAndLine.circle(x=testData.index, y=testData)

# only auto-range over the line and circle, not the bar
histAndLine.x_range.renderers = [l,c] 

enter image description here