尝试在 Matplotlib 中制作子图时绘图不正确

Plots draw incorrectly when attempting to make subplots in Matplotlib

我正在根据从 NetCDF 文件中提取的数据制作一些海洋温度和盐度图。它们被用作我使用 moviepy 库制作的动画中的帧。我正在使用的软件包:

from netCDF4 import Dataset # reads netCDF file
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap # basemap tools
from datetime import datetime, timedelta #for working with datetimes
import moviepy.editor as mpy # creates animation
from moviepy.video.io.bindings import mplfig_to_npimage # converts map to numpy array
from matplotlib.backends.backend_agg import FigureCanvasAgg # draws canvas so that map can be converted

当我自己画图时,它们看起来不错。这是盐度图的一个例子。

# map setup
fig = plt.figure()
fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9)
# Setup the map
m = Basemap(projection='merc', llcrnrlat=-38.050653, urcrnrlat=-34.453367,\
        llcrnrlon=147.996456, urcrnrlon=152.457344, lat_ts=20, resolution='h')
# draw stuff
m.drawcoastlines()
m.fillcontinents(color='black')
# plot salt
cs = m.pcolor(lons,lats,np.squeeze(salt), latlon = True ,vmin=salt_min, vmax=salt_max, cmap='viridis')
# plot colourbar
plt.colorbar()
# datetime title
plt.title('Regional - Salinity (PSU)\n' + frame_time.strftime("%Y-%m-%d %H:%M:%S") + ' | ' + str(fname) + '_idx: ' + str(frame_idx))
# stop axis from being cropped
plt.tight_layout()

但是我想并排绘制温度和盐度,但是当我绘制时,颜色条和数字并不像我预期的那样绘制。

# set up figure
fig = plt.figure()
fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9)

# Temperature figure
plt.subplot(1, 2, 1)
# Setup the map
m = Basemap(projection='merc', llcrnrlat=-38.050653, urcrnrlat=-34.453367,\
        llcrnrlon=147.996456, urcrnrlon=152.457344, lat_ts=20, resolution='h')
# draw stuff
m.drawcoastlines()
m.fillcontinents(color='black')
# plot salt
cs = m.pcolor(lons,lats,np.squeeze(temp), latlon = True ,vmin=temp_min, vmax=temp_max, cmap='plasma')
# plot colourbar
plt.colorbar()
# datetime title
plt.title('Regional - Temperature (Celcius)\n' + frame_time.strftime("%Y-%m-%d %H:%M:%S") + ' | ' + str(fname) + '_idx: ' + str(frame_idx))

# Salinity figure
plt.subplot(1, 2, 2)
# Setup the map
m = Basemap(projection='merc', llcrnrlat=-38.050653, urcrnrlat=-34.453367,\
        llcrnrlon=147.996456, urcrnrlon=152.457344, lat_ts=20, resolution='h')
# draw stuff
m.drawcoastlines()
m.fillcontinents(color='black')
# plot salt
cs = m.pcolor(lons,lats,np.squeeze(salt), latlon = True ,vmin=salt_min, vmax=salt_max, cmap='viridis')
# plot colourbar
plt.colorbar()
# datetime title
plt.title('Regional - Salinity (PSU)\n' + frame_time.strftime("%Y-%m-%d %H:%M:%S") + ' | ' + str(fname) + '_idx: ' + str(frame_idx))
# make layout nice
plt.tight_layout()

我希望它们与原始示例相似,但并排放置。我想我正确地使用了 subplot 函数,但我不知道如何修复它。有任何想法吗?谢谢。

注意:可能不是问题的关键,但我可能会提到每一帧都被转换为一个 numpy 数组,因为我稍后将图像传递给 moviepy 中的函数以制作动画。

# convert to array
canvas = FigureCanvasAgg(fig)
canvas.draw()
frame = np.fromstring(canvas.tostring_rgb(), dtype='uint8')
frame = frame.reshape(fig.canvas.get_width_height()[::-1] + (3,))

这是一个输出示例:

我认为这个答案会对您有所帮助:matplotlib colorbar in each subplot(可能重复)

它说要查看这个 matplotlib 示例页面:https://matplotlib.org/examples/images_contours_and_fields/pcolormesh_levels.html

您可以看到示例在使用 colorbar-method 时指定了 ax:

fig.colorbar(im, ax=ax0)

之前像这样分配 ax 变量的地方:

fig, (ax0, ax1) = plt.subplots(nrows=2)