Python 语言 用 Geopandas 绘制快递网点分布密度图 结合行政区划

Python阿木 发布于 2 天前 5 次阅读


Python Geopandas 绘制快递网点分布密度图结合行政区划

随着电子商务的快速发展,快递行业在我国经济中扮演着越来越重要的角色。快递网点的布局和分布对于提高配送效率、降低成本具有重要意义。本文将利用Python的Geopandas库,结合行政区划数据,绘制快递网点分布密度图,以直观展示快递网点的空间分布特征。

准备工作

在开始编写代码之前,我们需要准备以下数据:

1. 快递网点数据:包含网点名称、经纬度坐标等信息。
2. 行政区划数据:包含行政区划边界、名称等信息。

以下是所需的数据格式示例:

python
快递网点数据
network_data = [
{'name': '网点1', 'longitude': 116.4074, 'latitude': 39.9042},
{'name': '网点2', 'longitude': 121.4737, 'latitude': 31.2304},
... 更多网点数据
]

行政区划数据
district_data = [
{'name': '北京市', 'boundary': [(116.4074, 39.9042), (116.4074, 40.0), (116.5, 40.0), (116.5, 39.9)]},
{'name': '上海市', 'boundary': [(121.4737, 31.2304), (121.5, 31.2), (121.5, 31.1), (121.4, 31.1)]},
... 更多行政区划数据
]

安装Geopandas库

我们需要安装Geopandas库。由于您要求不使用pip安装,这里假设Geopandas库已经安装。

代码实现

1. 导入所需库

python
import geopandas as gpd
import matplotlib.pyplot as plt
from shapely.geometry import Point

2. 创建Geopandas DataFrame

python
创建快递网点DataFrame
network_gdf = gpd.GeoDataFrame(network_data, geometry=gpd.points_from_xy([x['longitude'] for x in network_data], [x['latitude'] for x in network_data]))

创建行政区划DataFrame
district_gdf = gpd.GeoDataFrame(district_data, geometry=gpd.Polygon([x['boundary'] for x in district_data]))

3. 绘制地图

python
创建地图
fig, ax = plt.subplots(1, 1, figsize=(10, 10))

绘制行政区划边界
district_gdf.plot(ax=ax, color='white', edgecolor='black')

绘制快递网点
network_gdf.plot(ax=ax, color='red', markersize=10)

设置标题和坐标轴标签
ax.set_title('快递网点分布密度图')
ax.set_xlabel('经度')
ax.set_ylabel('纬度')

显示地图
plt.show()

4. 计算密度

为了更直观地展示快递网点的分布密度,我们可以计算每个行政区划内的快递网点数量,并使用颜色深浅表示密度。

python
计算每个行政区划内的快递网点数量
network_gdf['district'] = network_gdf.intersect(district_gdf).apply(lambda x: x['name'] if not x.isnull() else None)
district_network_counts = network_gdf['district'].value_counts()

绘制密度图
fig, ax = plt.subplots(1, 1, figsize=(10, 10))

绘制行政区划边界
district_gdf.plot(ax=ax, color='white', edgecolor='black')

绘制快递网点密度
for district, count in district_network_counts.items():
district_data = district_gdf[district_gdf['name'] == district]
ax.text(district_data.geometry.centroid.x, district_data.geometry.centroid.y, str(count), fontsize=10, ha='center', va='center')

设置标题和坐标轴标签
ax.set_title('快递网点分布密度图')
ax.set_xlabel('经度')
ax.set_ylabel('纬度')

显示地图
plt.show()

总结

本文介绍了如何使用Python的Geopandas库绘制快递网点分布密度图,并结合行政区划数据展示快递网点的空间分布特征。通过计算每个行政区划内的快递网点数量,我们可以直观地了解快递网点的分布密度,为快递行业规划和优化提供参考。

在实际应用中,您可以根据需要调整代码,例如添加更多数据、调整颜色、添加图例等。Geopandas库还提供了丰富的功能,可以帮助您进行更复杂的地理空间分析。