首页 > 解决方案 > 如何在散景中同时使用 ColumnDataSource 和 LegendItem?

问题描述

我想使用散景创建具有这些功能的分类散点图:

  1. 悬停工具提示

  2. 情节区域外的图例,点击策略=“隐藏”

经过多次搜索,我可以分别实现功能#1和#2。

但我不知道如何使这两个功能同时工作。

工具提示只需要一个字形对象,但绘图区域外的图例需要一个 for 循环来创建用于生成 legend_items 的字形对象列表。

谢谢。

代码示例:

  1. 悬停工具提示可以通过使用 ColumnDataSources ( https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#heat-maps )来实现
import pandas as pd
from bokeh.sampledata.stocks import AAPL
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, output_file, show

df = pd.DataFrame(AAPL)
output_file("test.html")
p = figure(tools="hover")
source = ColumnDataSource(df)

p.scatter("high", "low", source=source)

p.hover.tooltips = [("Date","@date")]

show(p)
  1. 图例外的图例(将图例定位在带有 Bokeh 的图区之外
import pandas as pd

from bokeh.models import Legend, LegendItem
from bokeh.palettes import Spectral4
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT

output_file("test2.html")
p = figure(x_axis_type="datetime")
p_list = []

for data, name, color in zip([AAPL, IBM, MSFT, GOOG], ["AAPL", "IBM", "MSFT", "GOOG"], Spectral4):
    df = pd.DataFrame(data)
    df['date'] = pd.to_datetime(df['date'])
    p_list.append(p.line(df['date'], df['close'], line_width=2, color=color, alpha=0.8))

legend_items = [LegendItem(label=x, renderers=[p_list[i]]) for i, x in enumerate(["AAPL", "IBM", "MSFT", "GOOG"])]
legend_ = Legend(items=legend_items, click_policy="hide", location="center", label_text_font_size="12px")
p.add_layout(legend_, "right")

show(p)

标签: pythonbokeh

解决方案


import pandas as pd

from bokeh.models import Legend, LegendItem, ColumnDataSource
from bokeh.palettes import Spectral4
from bokeh.plotting import figure, show
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT

p = figure(x_axis_type="datetime", tools='hover')
p.hover.tooltips = [("Date", "@date{%F}"),
                    ("Open", "@open"),
                    ("Close", "@close")]
p.hover.formatters = {'@date': 'datetime'}

legend_items = []
for data, name, color in zip([AAPL, IBM, MSFT, GOOG],
                             ["AAPL", "IBM", "MSFT", "GOOG"],
                             Spectral4):
    data['date'] = pd.to_datetime(data['date']).values
    ds = ColumnDataSource(data)
    renderer = p.line('date', 'close', source=ds,
                      line_width=2, color=color, alpha=0.8)
    legend_items.append(LegendItem(label=name, renderers=[renderer]))

legend = Legend(items=legend_items, click_policy="hide",
                location="center", label_text_font_size="12px")
p.add_layout(legend, "right")

show(p)

如果您想为不同的股票提供不同的工具提示,您可以为每只股票创建一个悬停工具并在tools参数中指定它们。缺点 - 工具栏上会有多个悬停工具按钮。


推荐阅读