散景:如何使用GeoJSONDataSource和CategoricalColorMapper将图例添加到补丁字形中?

时间:2019-02-22 11:28:37

标签: python bokeh

我试图在Bokeh补丁图中添加图例,但最终只得到一个图例项(并带有错误的标签)。

我有一个带有多边形的形状文件。每个多边形都有一个名为“类别”的属性,该属性可以采用值“ A”,“ B”,“ C”,“ D”和“ E”。我将形状文件转换为geojson,随后使用CategoricalColorMapper根据其所在的“类别”向每个多边形添加颜色,从而创建了一个Bokeh补丁图。现在,我希望图例显示五个类别选项及其各自的颜色。

这是我的代码:

import geopandas as gpd
from bokeh.io import show, output_notebook, output_file, export_png
from bokeh.models import GeoJSONDataSource, CategoricalColorMapper, Legend, LegendItem
from bokeh.plotting import figure, reset_output
from bokeh.transform import factor_cmap
import selenium
import numpy as np

gdf = gpd.GeoDataFrame.from_file("test.shp")
gdf_json = gdf.to_json()
source_shape = GeoJSONDataSource(geojson=gdf_json)

cmap = CategoricalColorMapper(palette=["black", "purple", "pink", "brown", "blue"], factors=['A','B','C','D', 'E'])

p = figure(height=500, match_aspect=True,
    h_symmetry=False, v_symmetry=False, min_border=0)

p.patches('xs', 'ys', source=source_shape, fill_color={'field': 'category', 'transform': cmap},
             line_color='black', line_width=0.5, legend='category')
export_png(p, filename="map.png")

但是,我得到的输出如下: map.png output

图例仅显示一项,带有标签“ category”,而不是实际的类别名称。如何解决这个问题,使图例显示所有5个类别及其标签(A,B,C,D,E)?

2 个答案:

答案 0 :(得分:1)

似乎该图例当前无法与GeoJSONDataSource一起使用,因为还有一个尚未解决的未解决问题Legend not working with GeoJSONDataSource #5904

答案 1 :(得分:0)

此代码可以满足您的要求,但是,我认为直接操作GeoDataFrame而不是转换为JSON可能会更容易。该代码与Bokeh v1.0.4兼容。

from bokeh.models import GeoJSONDataSource, CategoricalColorMapper
from bokeh.plotting import figure, show
from bokeh.io import export_png
import geopandas as gpd
import random
import json

gdf = gpd.GeoDataFrame.from_file("Judete/Judete.shp")
gdf_json = gdf.to_json()
gjson = json.loads(gdf_json)

categories = ['A', 'B', 'C', 'D', 'E']
for item in gjson['features']:
    item['properties']['category'] = random.choice(categories)

source_shapes = {}
for category in categories:
    source_shapes[category] = {"type": "FeatureCollection", "features": []}

for item in gjson['features']:
    source_shapes[item['properties']['category']]['features'].append(item)

p = figure(match_aspect = True, min_border = 0,
           h_symmetry = False, v_symmetry = False,
           x_axis_location = None, y_axis_location = None)

cmap = CategoricalColorMapper(palette = ["orange", "purple", "pink", "brown", "blue"], 
                              factors = ['A', 'B', 'C', 'D', 'E'])
for category in categories:
    source_shape = GeoJSONDataSource(geojson = json.dumps(source_shapes[category]))
    p.patches('xs', 'ys', fill_color = {'field': 'category', 'transform': cmap},
                          line_color = 'black', line_width = 0.5,
                          legend = category, source = source_shape,)
p.legend.click_policy = 'hide'
show(p) # export_png(p, filename = "map.png")

结果:

enter image description here