如何在散景中同时使用 ColumnDataSource 和 LegendItem?

How to work with ColumnDataSource and LegendItem together in bokeh?

我想使用散景创建包含这些函数的分类散点图:

  1. 悬停工具提示

  2. 具有点击策略的绘图区外的图例="hide"

经过多次搜索,我可以分别实现功能#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. 剧情外的传说 ()
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)
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 参数中指定它们。缺点 - 工具栏上会有多个悬停工具按钮。