用户定义的Bokeh图例

时间:2018-03-14 10:35:09

标签: python matplotlib legend bokeh

我想做一些非常简单的事情,因为这个例子取自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()

我有数据显示类似于散景德州的例子,但是当创建图例时,由于shapefile中多边形的顺序,它会显示图例正确但是它遇到的多边形的顺序。例如。如果第一个多边形是第5类,则图例首先显示第5类。由于类是小数字,如果我可以手动操作将会有很多帮助。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

如果您提供了屏幕截图和代码,那会更好。我假设你在谈论下面的例子

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://bokeh.pydata.org/en/latest/docs/gallery/texas.html找到该代码。我刚添加了legend ='rate'来添加图例。

这将生成如下所示的数字 - enter image description here

右边的传说按照他们遇到的顺序排列。这个问题早已在Bokeh git中讨论过,而且这是故意选择的。 https://github.com/bokeh/bokeh/issues/1358

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

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

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]

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

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

希望这有帮助。

相关问题