用 Colomap 绘制线串 - Geopandas 和 Folium
Posted
技术标签:
【中文标题】用 Colomap 绘制线串 - Geopandas 和 Folium【英文标题】:Plotting Linestrings with a Colomap - Geopandas and Folium 【发布时间】:2022-01-19 23:29:11 【问题描述】:我有一个 geopandas 数据框,其中包含约 500 个线串和一个名为 total
的列,其中包含一个介于 0 和 1 之间的数字。
我想用取决于total
值的颜色在folium 地图上绘制线串。因此,我定义了一个颜色图如下:
colormap = cm.LinearColormap(colors=['lightblue','blue'])
我正在使用以下代码绘制所有内容:
m = folium.Map(zoom_start=10, tiles='CartoDB positron')
for _, r in gdf.iterrows():
geo_j = gpd.GeoSeries(r['geometry']).to_json()
geo_j = folium.GeoJson(data=geo_j,
style_function=lambda x:
'lineColor':colormap(r['total']),
'color': colormap(r['total']),
'fill':True,
'opacity': 1,
'fillColor': colormap(r['total']))
geo_j.add_to(m)
我尝试了所有线条颜色、颜色、填充颜色、不透明度等的组合,但即使colormap(r['total']
工作正常(总是检索不同的 rgb),所有线条总是用相同的颜色绘制:
谁能帮忙?
【问题讨论】:
【参考方案1】: 没有样本数据,因此在成对的伦敦地铁站之间生成了LineString 使用非常简单https://geopandas.org/en/v0.10.0/docs/user_guide/interactive_mapping.html 已使用生成的样本数据进行了演示import requests
import geopandas as gpd
import plotly.graph_objects as go
import itertools
import numpy as np
import pandas as pd
import shapely.geometry
# get geometry of london underground stations
gdf = gpd.GeoDataFrame.from_features(
requests.get(
"https://raw.githubusercontent.com/oobrien/vis/master/tube/data/tfl_stations.json"
).json()
)
# limit to zone 1 and stations that have larger number of lines going through them
gdf = (
gdf.loc[gdf["zone"].isin(["1", "2"]) & gdf["lines"].apply(len).gt(2)]
.reset_index(drop=True)
.rename(columns="id": "tfl_id", "name": "id")
)
# wanna join all valid combinations of stations...
combis = np.array(list(itertools.combinations(gdf.index, 2)))
# generate dataframe of all combinations of stations
gdf_c = (
gdf.loc[combis[:, 0], ["geometry", "id"]]
.assign(right=combis[:, 1])
.merge(
gdf.loc[:, ["geometry", "id"]],
left_on="right",
right_index=True,
suffixes=("_start_station", "_end_station"),
)
)
# generate linestrings between stations
gdf = gpd.GeoDataFrame(
geometry=gdf_c.select_dtypes("geometry").apply(shapely.geometry.LineString, axis=1),
data=gdf_c,
crs="EPSG:4326",
)
gdf["total"] = np.random.uniform(0, 1, len(gdf))
# now use explore that uses folium
gdf.explore("total", cmap="Blues", tiles="CartoDB positron")
【讨论】:
以上是关于用 Colomap 绘制线串 - Geopandas 和 Folium的主要内容,如果未能解决你的问题,请参考以下文章