您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python如何根据站点列表绘制站坐标全球分布图
## 引言
在全球气象观测、地震监测、生态研究等领域,经常需要将分布在世界各地的观测站点位置可视化展示。传统GIS软件操作复杂且难以批量处理,而Python凭借其丰富的地理信息处理库,可以快速实现站点坐标的可视化。本文将详细介绍如何使用Python的`cartopy`、`matplotlib`、`geopandas`等库,从站点数据准备到全球分布图生成的完整流程。
---
## 一、准备工作
### 1.1 所需工具库
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import geopandas as gpd
创建包含站点名称、经度、纬度的CSV文件stations.csv
:
station_id,latitude,longitude,country
NYC,40.7128,-74.0060,USA
LON,51.5074,-0.1278,UK
TOK,35.6762,139.6503,Japan
SYD,-33.8688,151.2093,Australia
...(更多示例数据)
df = pd.read_csv('stations.csv')
print(df.head())
# 检查缺失值
print(df.isnull().sum())
lon_min, lon_max = df['longitude'].min(), df['longitude'].max()
lat_min, lat_max = df['latitude'].min(), df['latitude'].max()
# 自动扩展10%边界
lon_buffer = (lon_max - lon_min) * 0.1
lat_buffer = (lat_max - lat_min) * 0.1
plt.figure(figsize=(15, 10))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_global()
ax.coastlines()
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.BORDERS, linestyle=':')
ax.add_feature(cfeature.LAKES, alpha=0.5)
ax.add_feature(cfeature.RIVERS)
scatter = ax.scatter(
x=df['longitude'],
y=df['latitude'],
c='red',
s=20,
transform=ccrs.PlateCarree(),
label='Weather Stations'
)
plt.legend()
plt.title('Global Distribution of Observation Stations')
plt.grid()
countries = df['country'].unique()
colors = plt.cm.tab20(np.linspace(0, 1, len(countries)))
for country, color in zip(countries, colors):
subset = df[df['country'] == country]
ax.scatter(
subset['longitude'],
subset['latitude'],
color=color,
label=country,
s=15,
transform=ccrs.PlateCarree()
)
from scipy.stats import gaussian_kde
kde = gaussian_kde(np.vstack([df['longitude'], df['latitude']]))
xgrid = np.linspace(-180, 180, 100)
ygrid = np.linspace(-90, 90, 50)
X, Y = np.meshgrid(xgrid, ygrid)
Z = kde(np.vstack([X.ravel(), Y.ravel()])).reshape(X.shape)
ax.contourf(X, Y, Z, transform=ccrs.PlateCarree(), alpha=0.3)
import plotly.express as px
fig = px.scatter_geo(df,
lat='latitude',
lon='longitude',
hover_name='station_id',
projection="natural earth")
fig.show()
gl = ax.gridlines(
crs=ccrs.PlateCarree(),
draw_labels=True,
linewidth=1,
color='gray',
alpha=0.5
)
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
scalebar = AnchoredSizeBar(
ax.transData,
size=2000, # 2000km
label='2000 km',
loc='lower left'
)
ax.add_artist(scalebar)
ax.stock_img() # 使用NASA的Blue Marble底图
# 或使用ESRI的影像服务
ax.add_wms(wms='https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/',
layers=['0'])
plt.savefig('global_stations.png', dpi=300, bbox_inches='tight')
plt.savefig('global_stations.pdf', format='pdf')
import matplotlib.animation as animation
def update(frame):
ax.view_init(elev=10, azim=frame)
return ax,
ani = animation.FuncAnimation(
plt.gcf(),
update,
frames=range(0, 360, 5),
interval=50
)
ani.save('rotation.mp4', writer='ffmpeg')
# 完整实现代码(整合所有功能)
import pandas as pd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
# 数据加载
df = pd.read_csv('stations.csv')
# 创建地图
plt.figure(figsize=(16, 12))
ax = plt.axes(projection=ccrs.Robinson())
ax.set_global()
# 添加地理要素
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.BORDERS, linestyle=':')
# 绘制站点
sc = ax.scatter(
df['longitude'],
df['latitude'],
c=df.index,
cmap='viridis',
s=50,
transform=ccrs.PlateCarree(),
edgecolor='black'
)
# 添加色标
plt.colorbar(sc, label='Station ID')
# 添加标题
plt.title('Global Distribution of Monitoring Stations\n', fontsize=16)
# 保存输出
plt.savefig('final_map.jpg', dpi=300, quality=90)
plt.show()
通过Python的地理可视化工具链,我们可以轻松实现专业级的站点全球分布图。本文介绍的方法可以进一步扩展: - 结合时间维度制作动画 - 集成实际观测数据(如温度、降水)进行多维可视化 - 部署为Web交互应用(使用Dash/Leaflet)
建议读者尝试调整地图投影方式(如Mercator
、Mollweide
等),探索最适合特定数据集的可视化方案。
“`
注:本文实际约3000字,完整4000字版本可扩展以下内容: 1. 不同地图投影的对比(增加500字) 2. 使用Basemap与Cartopy的详细对比(增加300字) 3. 常见错误排查章节(增加200字)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。