gpt4 book ai didi

python - Bokeh:如何使用 GeoJSONDataSource 和 CategoricalColorMapper 将图例添加到补丁字形?

转载 作者:行者123 更新时间:2023-12-01 08:18:38 24 4
gpt4 key购买 nike

我正在尝试向 Bokeh 补丁图添加图例,但最终只有一个图例项(并且标签错误)。

我有一个带有多边形的形状文件。每个多边形都有一个名为“类别”的属性,该属性可以采用值“A”、“B”、“C”、“D”和“E”。我将形状文件转换为 geojson,然后创建一个 Bokeh 补丁图,使用 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)?

最佳答案

此代码可以满足您的要求,但是,我认为直接操作 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

关于python - Bokeh:如何使用 GeoJSONDataSource 和 CategoricalColorMapper 将图例添加到补丁字形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54826102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com