如何在 Matplotlib 中的地圖上繪製時區


讓我們考慮一下必須處理實際時間的資料。為了在地圖上繪製時區,我們可以在 Python 中使用“cartopy”或“metPy”包。但是,我們可以使用命令在 Anaconda 環境中安裝“cartopy”包:

conda install -c conda-forge cartopy

或者

conda install -c conda-forge metpy

現在,讓我們看看如何使用 Matplotlib 在地圖中繪製時區。

示例

import numpy as np
import cartopy.crs as ccrs
import matplotlib.animation as animation
import matplotlib.pyplot as plt

#Defining the plot size and axes
plt.figure(figsize=(10, 9))
ax = plt.axes(projection=ccrs.PlateCarree())

#Apply the color for the natural Earth sourced from cartopy package
ax.stock_img()
ax.coastlines(zorder=1)

#Reading the timezone using ShapelyFeature of Cartopy
shape_feature = ShapelyFeature(Reader('ne_10m_time_zones.shp').geometries(),
   ccrs.PlateCarree(), edgecolor='black')

# Plot the feature on the map
ax.add_feature(shape_feature, alpha=0.4, zorder=5, lw=1)
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
   linewidth=2, color='gray', alpha=0.5, linestyle='--')

#Apply the gridlines to separate the timezones
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
   linewidth=2, color='black', alpha=0.5, linestyle='--')

#Turn off all the axes excluding bottom
gl.xlabels_top = False
gl.ylabels_left = False
gl.ylabels_right = False

#Apply fixed locations with the tickable objects
gl.xlocator = mticker.FixedLocator(np.linspace(-180, 180, 25))
gl.xlabel_style = {'size': 10, 'color': 'blue'}
ax.set_title('Global Time Zones', size=15, color='g')

#Display the plots
plt.show()

輸出

執行以上程式碼片段將生成輸出,如下所示:

更新於: 2021 年 2 月 23 日

340 次瀏覽

啟動您的 職業生涯

完成課程後獲取認證

開始
廣告
© . All rights reserved.