如何将悬停突出显示添加到Bokeh步骤图表

时间:2017-08-03 05:45:28

标签: python visualization bokeh

我正在努力尝试复制类似于此http://fortune.com/fortune500/visualizations/?iid=recirc_f500landing-zone1

中第二个图表的代码

Bokeh中有默认的步骤图,但它不想让我添加字形。

我想要像这样的代码

from bokeh.charts import Step, show, output_file

# build a dataset where multiple columns measure the same thing
data = dict(
       stamp=[.33, .33, .34, .37, .37, .37, .37, .39, .41, .42,
              .44, .44, .44, .45, .46, .49, .49],
       postcard=[.20, .20, .21, .23, .23, .23, .23, .24, .26, .27,
                 .28, .28, .29, .32, .33, .34, .35]
   )

# create a step chart where each column of measures receives a unique color and dash style
step = Step(data, y=['stamp', 'postcard'],
        dash=['stamp', 'postcard'],
        color=['stamp', 'postcard'],
        title="U.S. Postage Rates (1999-2015)",
        ylabel='Rate per ounce', legend=True)

selected_line = Line(line_alpha=1, line_color="firebrick")
nonselected_line = Line(line_alpha=0.2, line_color="blue")

step.add_glyph(data,
           step,
           selection_glyph=selected_line,
           nonselection_glyph=nonselected_line
)

output_file("steps.html")

show(step)

我已经尝试过这个页面http://bokeh.pydata.org/en/latest/docs/user_guide/styling.html#selected-and-unselected-glyphs的每种方式有没有一种方法可以在没有图表库的情况下构建这个图?

1 个答案:

答案 0 :(得分:1)

步骤图 要在没有bokeh.charts库的情况下创建此项,您只需使用多行,请参阅http://bokeh.pydata.org/en/latest/docs/user_guide/plotting.html#multiple-lines。您只需为每个y手动创建相应的x值。

基本上,如果y值改变,它应该具有与前一个y值相同的x值,否则递增x值。这应该创建正确的数据。

悬停时的高亮显示: 您可以使用多行字形非常接近所需的效果。 它具有内置的悬停颜色和alpha设置,因此很容易处理。它唯一不做的是捕捉到最近的线。不确定是否有可能没有自定义的JavaScript,但我可能是错的。

下面附带的示例代码。

from bokeh.plotting import figure, show
from bokeh.models import HoverTool
from bokeh.models import ColumnDataSource

p = figure(plot_width=400, plot_height=400,y_range=(0.2,0.5))


y_vals = [0.22,0.22,0.25,0.25,0.26,0.26,0.27,0.27]
y_vals2 = [y*1.4 for y in y_vals]
x_vals = [0,1,1,2,2,2,2,3]
data_dict = {'x':[x_vals,x_vals],
             'y':[y_vals,y_vals2],
             'color':["firebrick", "navy"],
             'alpha':[0.1, 0.1]}

source = ColumnDataSource(data_dict)

p.multi_line('x','y',source=source,
             color='color', alpha='alpha', line_width=4,
             hover_line_alpha=1.0,hover_line_color='color')

p.add_tools(HoverTool(show_arrow=False,
                      line_policy='nearest',
                      tooltips=None))
show(p)