Python输入 ax.add_feature(cfeature.LAND,facecolor='grey',zorder=1)为什么报错positional argument follows keyword argument
时间: 2024-05-15 14:19:04 浏览: 14
这个报错的原因是你在使用函数时,将带有默认参数的参数放在了不带默认参数的参数之前。在这个例子中,`facecolor` 是一个默认参数并且已经指定了值,但是在它的后面却出现了一个不带默认参数的参数 `cfeature.LAND`。这会导致 Python 无法确定哪个参数是你想要传递给 `add_feature()` 函数的位置参数,从而导致了报错。要解决这个问题,你可以将带有默认参数的参数放在不带默认参数的参数之后,或者使用指定参数名的方式来传递参数。比如,修改成这样就不会报错了:
```python
ax.add_feature(cfeature.LAND, zorder=1, facecolor='grey')
```
相关问题
优化这个代码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)` 函数来计算和绘制温度距平图了。
ax.add_subplot(212,facecolor='#4f4f4f',alpha=0.3) plt.pie(city_counts_top20.values,labels=city_counts_top20.index,autopct='%1.1f%%',pctdistance=0.8,textprops={'color':'yellow'}) plt.tight_layout() plt.show()
这段代码的功能是创建一个带有底色和透明度的子图,并在子图中绘制一个饼图。
具体来说,`ax.add_subplot(212,facecolor='#4f4f4f',alpha=0.3)`创建了一个大小为2x1的子图区域,并将子图的背景色设置为灰色(`#4f4f4f`),透明度设置为0.3,其中的`(2,1,2)`表示这是第二个子图。
接下来,`plt.pie()`函数绘制了一个饼图,其中`city_counts_top20.values`是饼图中每个扇形的大小,`city_counts_top20.index`是饼图中每个扇形的标签,`autopct='%1.1f%%'`指定了百分比的显示格式,`pctdistance=0.8`指定了百分比与圆心之间的距离,`textprops={'color':'yellow'}`指定了标签的颜色为黄色。
最后,`plt.tight_layout()`函数用于自动调整子图的布局,`plt.show()`函数用于显示图形。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)