如何用GeoJSONDataSource和CategoricalColorMapper为补丁glyph添加图例?

2024-05-13 05:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为Bokeh patches图形添加图例,但最终只有一个图例项(并且标签错误)。在

我有一个多边形的形状文件。每个多边形都有一个名为“category”的属性,可以采用值“A”、“B”、“C”、“D”和“E”。我将形状文件转换为geojson,然后创建一个Bokeh patches图形,使用CategoricalColorMapper为每个多边形添加颜色,这取决于它所在的“类别”。现在我希望图例显示五个类别的选项和它们各自的颜色。在

我的代码是:

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

图例只显示一个项目,标签为“类别”,而不是实际的类别名称。如何修复此问题,使图例显示所有5个类别及其标签(A、B、C、D、E)?在


Tags: fromimportjsonoutputpngbokeh标签多边形
1条回答
网友
1楼 · 发布于 2024-05-13 05:12:44

这段代码可以满足您的需要,但是,我认为直接操作GeoDataFrame要比转换为JSON更容易。此代码与bokehv1.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

相关问题 更多 >