繁体   English   中英

如何在 Python 中使用 matplotlib 的 imshow 绘制 xarray 数据集时删除子图的边框/框架?

[英]How can I remove borders/frames of subplots while plotting xarray dataset using imshow of matplotlib in Python?

我从NASA 网站下载了一个名为 gistemp1200_GHCNv4_ERSSTv5.nc.gz 的 netCDF 文件

我使用包含温度异常数据的 xarray 打开数据。

import xarray as xr
file = "../data/gistemp1200_GHCNv4_ERSSTv5.nc"
xr_df = xr.open_dataset(file)

xr_df_annual = xr_df.resample(time = "Y").mean()

anomaly = xr_df_annual["tempanomaly"]

anomaly如下所示: 在此处输入图像描述

它包含相对于特定时间段的年温度异常值。

我想以子图的形式绘制四年的年温度值。 我使用以下代码:

fig, axs = plt.subplots(2, 2, figsize = (10, 10))

fig.suptitle("Temperature anomaly in the end of last four decades\n relative to 1951-1980")

def get_plot(year, i, j, k):
 
    ax = fig.add_subplot(2, 2, k, 
                         projection = ccrs.PlateCarree())
    
    ax.add_feature(NaturalEarthFeature('cultural', 'admin_0_countries', '10m'),
                       facecolor='none', edgecolor='black')

    ax.set_extent([-150, 150, -55, 85])
    
    xr_df_sub = anomaly.loc[f"{year}-12-31"]
    
    ax.set_title(f"{year}")
    
    ax.set_axis_off()
    
    xr.plot.imshow(xr_df_sub,
                  ax = ax,
                  add_labels = False,
                  vmin = -4, vmax = 4,
                  cmap = "coolwarm",
                   add_colorbar = False,
                  interpolation = "bicubic")
    
    
axs[0, 0] = get_plot(1990, 0, 0, 1)

axs[0, 1] = get_plot(2000, 0, 1, 2)

axs[1, 0] = get_plot(2010, 0, 1, 3)


axs[1, 1] = get_plot(2020, 0, 1, 4)

# add colorbar
cax = fig.add_axes([0.92, 0.15, 0.01, 0.7]) #[left, bottom, width, height]
sm = plt.cm.ScalarMappable(cmap='coolwarm',
                           norm=plt.Normalize(vmin= -4, vmax= 4))

# fake up the array of the scalar mappable.
sm._A = []
lgd=fig.colorbar(sm, cax=cax, extend = "both"
                 ).set_label("°C", rotation=0,y=1.1, labelpad= -35)


plt.show()

我为每个子图创建了一个名为get_plot(year, i, j, k)的函数。 i , j指的是行号和列号, k指的是子图的索引号。 绘制给定year的温度异常的函数。

我得到了一个图,如下所示: 在此处输入图像描述

这是所需的情节,但是,我为每个要删除的子情节获得了外部黑色框架。 我使用了以下代码:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

但是,它不会改变任何东西。 我也试过

fig.patch.set_visible(False)

它也没有改变任何东西。

如何删除每个子图的 x 轴和 y 轴上 0 到 1 的外部边界? 另外,我想获得有关使子图彼此靠近的建议?

根据 Dahn 的建议,我发现我使用了plt.subplot()并再次使用了fig.add_subplot()两次。

我解决了如下问题:

fig = plt.figure(figsize = (10, 10))

fig.suptitle("过去四个十年末的温度异常\n相对于 1951-1980", y = 0.8)

plt.subplots_adjust(底部 = 0.3,顶部 = 0.7,wspace=0.1,hspace=0.25)

def get_plot(year, i, j, k):
 
    ax = fig.add_subplot(2, 2, k, 
                         projection = ccrs.PlateCarree())
    
    ax.add_feature(NaturalEarthFeature('cultural', 'admin_0_countries', '10m'),
                       facecolor='none', edgecolor='black')

    ax.set_extent([-150, 150, -55, 85])
    
    xr_df_sub = anomaly.loc[f"{year}-12-31"]
    
    ax.set_title(f"{year}")
    
    ax.axis("off")
    
    ax = xr.plot.imshow(xr_df_sub,

              add_labels = True,
              vmin = -4, vmax = 4,
              cmap = "coolwarm",
               add_colorbar = False,
              interpolation = "bicubic",
              )
    
    return ax
    
ax[0, 0] = get_plot(1990, 0, 0, 1)

ax[0, 1] = get_plot(2000, 0, 1, 2)

ax[1, 0] = get_plot(2010, 0, 1, 3)


ax[1, 1] = get_plot(2020, 0, 1, 4)

# add colorbar
cax = fig.add_axes([0.92, 0.3, 0.02, 0.5]) #[left, bottom, width, height]
sm = plt.cm.ScalarMappable(cmap='coolwarm',
                           norm=plt.Normalize(vmin= -4, vmax= 4))

# fake up the array of the scalar mappable.
sm._A = []
lgd=fig.colorbar(sm, cax=cax, extend = "both"
                 ).set_label("°C", rotation=0,y=1.1, labelpad= -35)

plt.show()

我得到了所需的情节,如下所示: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM