import matplotlib.pyplot as plt import matplotlib.gridspec as grid_spec plt.rcParams['savefig.facecolor'] = '0.8' def draw_plot(ax_p,front_sized=12): ax_p.plot([1,2]) ax_p.locator_params(nbins=3) ax_p.set_xlabel('x-label',fontsize=font_size) ax_p.set_ylabel('y-label',fontsize=font_size) ax_p.set_title('Title',fontsize=font_size) plt.close('all') fig,ax = plt.subplots() draw_plot(ax,font_size=24) plt.show()
时间: 2024-04-14 10:32:01 浏览: 28
这段代码使用了Matplotlib库来绘制一个简单的图表。首先,导入了必要的库和模块。然后,设置了保存图像的背景色为灰色。接下来,定义了一个名为`draw_plot`的函数,该函数接受一个`ax_p`参数作为子图对象,并设置了一些绘图的属性,如绘制一条折线图、设置x轴和y轴标签、设置图表标题等。最后,创建了一个图形对象和子图对象,并调用`draw_plot`函数来绘制图表,最后显示图表。
注意:在代码中,`font_size`参数的命名与函数定义中的参数名不一致,应该将`front_sized`改为`font_size`以保持一致性。
相关问题
优化下面代码import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(22 / 2.54, 18 / 2.54), facecolor='white', edgecolor='w', linewidth=2) plt.rcParams['xtick.direction'] = 'in' plt.rcParams['ytick.direction'] = 'in' ax = plt.gca() x = np.linspace(0, 12, 12) y = np.random.random(len(x)) * 16.5 + 6 p1, = plt.plot(x, y, '>', color='orange') p2, = plt.plot(x, y, '-', color='cyan') plt.title('深圳市24小时的平均风速', fontfamily='SimSun', fontsize=12) # fontstyle="italic" 斜体 ax.set_xlabel('时间(h)', fontfamily='SimSun') ax.set_ylabel('平均风速(km/h)', fontfamily='SimSun') ax.xaxis.set_ticks(np.linspace(0, 12, 13)) ax.yaxis.set_ticks(np.linspace(8, 22, 8)) ax.xaxis.set_ticklabels(['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00', '00:00'], rotation=45) plt.savefig('fig.pdf') plt.show()
Here is the optimized code:
```python
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
x = np.linspace(0, 12, 12)
y = np.random.random(len(x)) * 16.5 + 6
fig, ax = plt.subplots(figsize=(22/2.54, 18/2.54), facecolor='white', edgecolor='w', linewidth=2)
ax.plot(x, y, '>', color='orange', label='平均风速')
ax.plot(x, y, '-', color='cyan', label='平均风速')
ax.set_title('深圳市24小时的平均风速', fontfamily='SimSun', fontsize=12)
ax.set_xlabel('时间(h)', fontfamily='SimSun')
ax.set_ylabel('平均风速(km/h)', fontfamily='SimSun')
ax.set_xticks(np.arange(0, 13, 2))
ax.set_yticks(np.arange(8, 23, 2))
ax.set_xticklabels(['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00', '00:00'], rotation=45)
ax.legend(loc='best')
plt.savefig('fig.pdf')
plt.show()
```
In this optimized code, we:
- Use `subplots` to create a figure and axes instance at the same time.
- Add labels to the `plot` function to create a legend for the plot.
- Use `np.arange` instead of `np.linspace` to set the tick locations for the x and y axis.
- Use `ax.legend` to add a legend to the plot.
优化这个代码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)` 函数来计算和绘制温度距平图了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)