ax.add_feature(cfeature.COASTLINE.with_scale('110m'),lw=1)
时间: 2024-03-18 08:46:01 浏览: 81
这段代码使用了 Cartopy 库中的 add_feature 函数,向地图中添加了一个 COASTLINE 特征,with_scale('110m') 指定了特征的尺度为 110 米。lw=1 指定了 COASTLINE 特征的线宽为 1。COASTLINE 特征是地图上的海岸线特征,会在地图上绘制出陆地和海洋的交界线。
相关问题
f_path = r"E:\gra_thesis\sum_pre_data_new\grid_nc\AMJ_pre_total_precip.nc" f = xr.open_dataset(f_path) f # %% lon = f['lon'] lat = f['lat'] data= f['precip'] data_mean = np.mean(data, 0) # %% shp_path = r"C:\Users\86133\Desktop\thesis\2020国家级行政边界\China_province.shp" sf = shapefile.Reader(shp_path) shp_reader = Reader(shp_path) sf.records() region_list = [110000, 120000, 130000,140000,150000,210000,220000, 230000, 310000, 320000,330000,340000,350000,360000, 370000, 410000, 420000,430000,440000,450000,460000, 500000, 510000, 520000,530000,540000,610000,620000, 630000, 640000, 650000,710000,810000,820000] # %% proj = ccrs.PlateCarree() extent = [105, 125, 15, 30] fig, ax = plt.subplots(1, 1, subplot_kw={'projection': proj}) ax.set_extent(extent, proj) # ax.add_feature(cfeature.LAND, fc='0.8', zorder=1) ax.add_feature(cfeature.COASTLINE, lw=1, ec="k", zorder=2) ax.add_feature(cfeature.OCEAN, fc='white', zorder=2) ax.add_geometries(shp_reader.geometries(), fc="None", ec="k", lw=1, crs=proj, zorder=2) ax.spines['geo'].set_linewidth(0.8) ax.tick_params(axis='both',which='major',labelsize=9, direction='out',length=2.5,width=0.8,pad=1.5, bottom=True, left=True) ax.tick_params(axis='both',which='minor',direction='out',width=0.5,bottom=True,left=True) ax.set_xticks(np.arange(105, 130, 5)) ax.set_yticks(np.arange(15, 40, 5)) ax.xaxis.set_major_formatter(LongitudeFormatter()) ax.yaxis.set_major_formatter(LatitudeFormatter()) cf = ax.contourf(lon, lat, data_mean, extend='both', cmap='RdBu') cb = fig.colorbar(cf, shrink=0.9, pad=0.05)解释这段代码
这是Python中的代码。它使用xarray库中的open_dataset函数来打开一个名为AMJ_pre_total_precip.nc的NetCDF文件。文件位于E:\gra_thesis\sum_pre_data_new\grid_nc目录中。函数返回一个数据集,命名为f。
优化这个代码import xarray as xr import netCDF4 as nc import pandas as pd import numpy as np import datetime import matplotlib.pyplot as plt import cartopy.mpl.ticker as cticker import cartopy.crs as ccrs import cartopy.feature as cfeature ds = xr.open_dataset('C:/Users/cindy/Desktop/SP.nc', engine='netcdf4') # 读取原始数据 ds_temp = xr.open_dataset('C:/Users/cindy/Desktop/SP.nc') # 区域提取* south_asia = ds_temp.sel(latitude=slice(38, 28), longitude=slice(75, 103)) indian_ocean = ds_temp.sel(latitude=slice(5, -15), longitude=slice(60, 100)) # 高度插值 south_asia_200hpa = south_asia.t.interp(level=200) indian_ocean_200hpa = indian_ocean.t.interp(level=200) south_asia_400hpa = south_asia.t.interp(level=400) indian_ocean_400hpa = indian_ocean.t.interp(level=400) # 区域平均 TTP = south_asia_400hpa.mean(dim=('latitude', 'longitude'))#.values TTIO = indian_ocean_400hpa.mean(dim=('latitude', 'longitude'))# TTP_200hpa = south_asia_200hpa.mean(dim=('latitude', 'longitude')) TTIO_200hpa = indian_ocean_200hpa.mean(dim=('latitude', 'longitude')) tlup=(TTP-TTIO)-(TTP_200hpa-TTIO_200hpa)-(-5.367655815) # 定义画图区域和投影方式 fig = plt.figure(figsize=[10, 8]) ax = plt.axes(projection=ccrs.PlateCarree()) # 添加地图特征 ax.set_extent([60, 140, -15, 60], crs=ccrs.PlateCarree()) ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidths=0.5) ax.add_feature(cfeature.LAND.with_scale('50m'), facecolor='lightgray') ax.add_feature(cfeature.OCEAN.with_scale('50m'), facecolor='white') # 画距平场 im = ax.contourf(TTP_200hpa, TTP, tlup, cmap='coolwarm', levels=np.arange(-4, 4.5, 0.5), extend='both') # 添加色标 cbar = plt.colorbar(im, ax=ax, shrink=0.8) cbar.set_label('Temperature anomaly (°C)') # 添加经纬度坐标轴标签 ax.set_xticks(np.arange(60, 105, 10), crs=ccrs.PlateCarree()) ax.set_yticks(np.arange(-10, 40, 10), crs=ccrs.PlateCarree()) lon_formatter = cticker.LongitudeFormatter() lat_formatter = cticker.LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) # 添加标题和保存图片 plt.title('Temperature anomaly at 400hPa over South Asia and the Indian Ocean') plt.savefig('temperature_anomaly.png', dpi=300) plt.show()
1. 首先,可以将多个导入语句合并为一行,以提高代码的可读性。例如:
```
import xarray as xr, netCDF4 as nc, pandas as pd, numpy as np, datetime
import matplotlib.pyplot as plt
import cartopy.mpl.ticker as cticker, cartopy.crs as ccrs, cartopy.feature as cfeature
```
2. 可以在代码中删除不必要的变量,例如 `ds` 和 `ds_temp` 都是指向同一个文件的数据集,因此只需要保留一个即可。
3. 对于数据集的区域提取和高度插值操作,可以将它们合并成一个链式操作,以减少代码行数。例如:
```
south_asia = ds.sel(latitude=slice(38, 28), longitude=slice(75, 103)).t.interp(level=200)
indian_ocean = ds.sel(latitude=slice(5, -15), longitude=slice(60, 100)).t.interp(level=200)
```
4. 对于计算平均值的操作,可以使用 `reduce` 函数,以减少代码行数。例如:
```
TTP, TTIO = np.array([south_asia_400hpa, indian_ocean_400hpa]).reduce(lambda x, y: x.mean(dim=('latitude', 'longitude')), axis=0)
TTIO_200hpa = indian_ocean_200hpa.mean(dim=('latitude', 'longitude'))
```
5. 可以将一些常量定义为全局变量或者类变量,以方便后续使用。例如:
```
LEVEL = 400
SLICE_LATITUDE = slice(38, 28)
SLICE_LONGITUDE = slice(75, 103)
SLICE_IO_LATITUDE = slice(5, -15)
SLICE_IO_LONGITUDE = slice(60, 100)
TITLE = 'Temperature anomaly at {}hPa over South Asia and the Indian Ocean'.format(LEVEL)
```
6. 可以将绘图的代码封装为一个函数,以提高代码的可读性和复用性。例如:
```
def plot_temperature_anomaly(TTP, TTIO, TTP_200hpa, TTIO_200hpa, tlup):
fig = plt.figure(figsize=[10, 8])
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([60, 140, -15, 60], crs=ccrs.PlateCarree())
ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidths=0.5)
ax.add_feature(cfeature.LAND.with_scale('50m'), facecolor='lightgray')
ax.add_feature(cfeature.OCEAN.with_scale('50m'), facecolor='white')
im = ax.contourf(TTP_200hpa, TTP, tlup, cmap='coolwarm', levels=np.arange(-4, 4.5, 0.5), extend='both')
cbar = plt.colorbar(im, ax=ax, shrink=0.8)
cbar.set_label('Temperature anomaly (°C)')
ax.set_xticks(np.arange(60, 105, 10), crs=ccrs.PlateCarree())
ax.set_yticks(np.arange(-10, 40, 10), crs=ccrs.PlateCarree())
lon_formatter = cticker.LongitudeFormatter()
lat_formatter = cticker.LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
plt.title(TITLE)
plt.savefig('temperature_anomaly.png', dpi=300)
plt.show()
```
7. 最后,可以将所有操作封装为一个函数,以方便调用。例如:
```
def calculate_and_plot_temperature_anomaly(filename):
ds = xr.open_dataset(filename)
south_asia = ds.sel(latitude=SLICE_LATITUDE, longitude=SLICE_LONGITUDE).t.interp(level=LEVEL)
indian_ocean = ds.sel(latitude=SLICE_IO_LATITUDE, longitude=SLICE_IO_LONGITUDE).t.interp(level=LEVEL)
south_asia_200hpa = south_asia.t.interp(level=200)
indian_ocean_200hpa = indian_ocean.t.interp(level=200)
TTP, TTIO = np.array([south_asia, indian_ocean]).reduce(lambda x, y: x.mean(dim=('latitude', 'longitude')), axis=0)
TTP_200hpa = south_asia_200hpa.mean(dim=('latitude', 'longitude'))
TTIO_200hpa = indian_ocean_200hpa.mean(dim=('latitude', 'longitude'))
tlup=(TTP-TTIO)-(TTP_200hpa-TTIO_200hpa)-(-5.367655815)
plot_temperature_anomaly(TTP, TTIO, TTP_200hpa, TTIO_200hpa, tlup)
```
这样,我们就可以通过调用 `calculate_and_plot_temperature_anomaly(filename)` 函数来计算和绘制温度距平图了。
阅读全文