如何在Bokeh的Box图中添加水平线(`Span`)?

时间:2016-09-10 14:22:01

标签: python pandas dataframe data-visualization bokeh

我想要的是使用bar chart渲染horizontal line,这样我就可以看到哪些值(以条形表示)超过了某个阈值(水平线)。我的数据由Pandas数据帧表示。

from bokeh.plotting import figure, output_file, show
from bokeh.charts import Bar
from bokeh.models import Span
from bokeh.io import save
from pandas import DataFrame

output_file('tmp_file')

p = figure(plot_width=800, plot_height=600)

rows = [(1,'2004-01-15', 10), (2,'2004-02-21', 15)]
headers = ['id', 'date', 'value']

df = DataFrame.from_records(rows, columns=headers)
bar = Bar(df, 'date', values='value', agg='mean')

treshold = 12

hline = Span(location=treshold, dimension='width', line_color='red', line_width=3)

p.renderers.extend([hline, bar])
save(p)

我得到的执行:

File "/usr/lib/python3.4/site-packages/bokeh/core/properties.py", line 1056, in validate
    raise ValueError("expected an element of %s, got seq with invalid items %r" % (self, invalid))
ValueError: expected an element of List(Instance(Renderer)), got seq with invalid items [<bokeh.charts.chart.Chart object at 0x7fa0a4534f28>]

1 个答案:

答案 0 :(得分:2)

好的,我想出来了......

from bokeh.charts import Bar
from bokeh.models import Span
from bokeh.io import save, output_file, show
from pandas import DataFrame
output_file('tmp_file')

rows = [(1,'2004-01-15', 10), (2,'2004-02-21', 15)]
headers = ['id', 'date', 'value']

df = DataFrame.from_records(rows, columns=headers)
bar = Bar(df, 'date', values='value', agg='mean')

treshold = 12

hline = Span(location=treshold, dimension='width', line_color='red', line_width=3)

bar.renderers.extend([hline])
save(bar)