散景图例用户定义

Bokeh legend user defined

我想做一些非常简单的事情,例如取自 matplotlib Legend 文档但使用 Bokeh 的示例。

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])

plt.show()

我有数据要显示,类似于 bokeh texas 示例,但是在创建图例时,由于 shapefile 中多边形的顺序,它显示的图例是正确的,但显示的是它遇到的多边形的顺序。例如。如果第一个多边形是 class 5,则图例首先显示 class 5。由于 classes 的数量很少,如果我可以手动操作,将会有很大帮助。谁能帮忙?

如果能提供截图和代码就更好了。我假设你在谈论下面的例子

from bokeh.io import show
from bokeh.models import (
    ColumnDataSource,
    HoverTool,
    LogColorMapper
)
from bokeh.palettes import Viridis6 as palette
from bokeh.plotting import figure

from bokeh.sampledata.us_counties import data as counties
from bokeh.sampledata.unemployment import data as unemployment

palette.reverse()

counties = {
    code: county for code, county in counties.items() if county["state"] == "tx"
}

county_xs = [county["lons"] for county in counties.values()]
county_ys = [county["lats"] for county in counties.values()]
county_names = [county['name'] for county in counties.values()]
county_rates = [unemployment[county_id] for county_id in counties]



color_mapper = LogColorMapper(palette=palette)

source = ColumnDataSource(data=dict(
    x=county_xs,
    y=county_ys,
    name=county_names,
    rate=county_rates
))

TOOLS = "pan,wheel_zoom,reset,hover,save"

p = figure(
    title="Texas Unemployment, 2009", tools=TOOLS,
    x_axis_location=None, y_axis_location=None
)
p.grid.grid_line_color = None


p.patches('x', 'y', source=source,
          fill_color={'field': 'rate', 'transform': color_mapper},
          fill_alpha=0.7, line_color="white", line_width=0.5, legend = 'rate')

hover = p.select_one(HoverTool)
hover.point_policy = "follow_mouse"
hover.tooltips = [
    ("Name", "@name"),
    ("Unemployment rate)", "@rate%"),
    ("(Long, Lat)", "($x, $y)"),
]
show(p)

可以在

找到代码

https://docs.bokeh.org/en/latest/docs/gallery/texas.html

刚刚添加了图例='rate'添加图例。

这将生成如下所示的图形 -

右边的传说是按照他们遇到的顺序排列的。这个问题早在 Bokeh git 中就已经讨论过了,这是有意选择的。

https://github.com/bokeh/bokeh/issues/1358

这意味着,您必须更改遇到比率的顺序(还要更改其他变量的顺序)。

您可以在定义 4 个列表 county_xs、county_ys、county_names 和 county_rates 之后添加以下代码行。

t = sorted(zip(county_rates, county_xs, county_ys, county_names))

county_xs = [x for _, x, _, _ in t]
county_ys = [x for _, _, x, _ in t]
county_names = [x for _, _, _, x in t]
county_rates = [x for x, _, _, _ in t]

这是根据比率值对所有数组进行排序。这将为您提供所需格式的图例。

您可以使用任何自定义顺序,只需按该顺序对压缩列表进行排序

希望对您有所帮助。