python - 如何防止 Python 中的子图重叠?
问题描述
我在三个不同的子图中绘制各种参数。我的第二个和第三个子图重叠,我不明白是什么原因造成的。我已经指定了 ax1、ax2 和 ax3,我认为问题可能来自 fig.add_subplot() 但我不知道如何解决它。请参阅下面的代码以供参考。我只包括了设置图形和最终图的部分,因为所有三个图实际上都是以相同的方式生成的。我还附上了一张我希望修复的情节的图像。
# Convert dataframe to 2D maps
lon_grid, lat_grid = np.meshgrid(data.lon.unique(), data.lat.unique())
L_grid = data.L.values.reshape(len(data.lat.unique()), len(data.lon.unique()))
Lam_grid = data.lam.values.reshape(len(data.lat.unique()), len(data.lon.unique()))
R_grid = data.R2.values.reshape(len(data.lat.unique()), len(data.lon.unique()))
# Make figures
fig = plt.figure(figsize= (10, 30), facecolor='white')
ax1 = fig.add_subplot(1,1,1,projection=ccrs.PlateCarree())
ax2 = fig.add_subplot(2,1,2,projection=ccrs.PlateCarree())
ax3 = fig.add_subplot(3,1,3,projection=ccrs.PlateCarree())
# Draw coastlines, states and countries for plot 3
ax3.coastlines()
ax3.add_feature(cfeature.BORDERS)
ax3.add_feature(cfeature.STATES)
# Draw parallels and meridians for plot 3
parallels = np.arange(-90,91,30)
meridians = np.arange(-180,181,60)
gl = ax3.gridlines(crs=ccrs.PlateCarree(), draw_labels=False,
linewidth=2, color='gray', alpha=0.5, linestyle='--')
gl.xlocator = mticker.FixedLocator(meridians)
gl.ylocator = mticker.FixedLocator(parallels)
ax3.set_xticks(np.arange(-180,181,30), crs=ccrs.PlateCarree())
ax3.set_yticks(parallels, crs=ccrs.PlateCarree())
lon_formatter = LongitudeFormatter(zero_direction_label=True)
lat_formatter = LatitudeFormatter()
ax3.xaxis.set_major_formatter(lon_formatter)
ax3.yaxis.set_major_formatter(lat_formatter)
# Add Longitude wrap-around points at 0/360 for plot 3
cyclic_R_grid, cyclic_lons = cutil.add_cyclic_point(R_grid, coord=data.lon.unique())
c3 = ax3.contourf(cyclic_lons, data.lat.unique(), cyclic_R_grid, alpha = 1.0,
transform=ccrs.PlateCarree(), levels = np.arange(0,100), \
vmin = 0.0, vmax = 100.0)
# Overplot rigidity
c3_ = ax3.imshow(np.flip(R_grid, axis=1), interpolation = 'gaussian', alpha = 0.6, extent = (-180,180,-90,90))
cbar = plt.colorbar(c3, ax=ax3, fraction=0.025)
cbar.set_label('R')
plt.show()
解决方案
您添加错误的子图。fig.add_subplot
期望n_rows
, n_cols
,index
按该顺序。所以正确的定义是
fig = plt.figure(figsize= (10, 30), facecolor='white')
ax1 = fig.add_subplot(3,1,1,projection=ccrs.PlateCarree())
ax2 = fig.add_subplot(3,1,2,projection=ccrs.PlateCarree())
ax3 = fig.add_subplot(3,1,3,projection=ccrs.PlateCarree())
推荐阅读
- postgresql - 如何修改记录数组中的字段
- html - hidden=false 的 div 仍然隐藏
- postgresql - 如何在@query 注释中将事务设置为只读?
- reactjs - 如何在 React 中实现 Web 条形码扫描仪以在浏览器(桌面/移动)中工作?
- excel - 回车和换行未替换为 VBA 字符串
- java - Runnable run() 方法同步执行,Callable call() 方法异步执行。
- java - 切换到 targetSdkVersion 28 (Android) 时出现 DefaultHttpClient NoClassDefFoundError
- gulp - $ gulp -> gulp: 找不到命令,但是 $ npx gulp -> 有效吗?
- javascript - 从csv文件读取数据后,使用javascript将指数数转换为普通数
- keras - 通过在 keras 中使用预训练模型的权重进行微调来进行迁移学习