imshow colormap 图和副标题未在中心对齐

imshow colormap figure and the suptitle don't align in the center

这是一个很小的问题,但我还是想不通。 我正在使用 imshow 和 matplotlib 来绘制颜色图 - 但结果是图形和标题没有对齐:

我用于绘图的代码是:

fig, ax = plt.subplots(figsize=(27, 10))

cax1 = ax.imshow(reversed_df, origin='lower', cmap='viridis', interpolation = 'nearest', aspect=0.55)

ylabels = ['0:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00']
major_ticks = np.arange(0, 24, 3)
ax.set_yticks(major_ticks)
ax.set_yticklabels(ylabels, fontsize = 15)

xlabels = ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan17']
xmajor_ticks = np.arange(0,12,1)
ax.set_xticks(xmajor_ticks)
ax.set_xticklabels(xlabels, fontsize = 15)
fig.autofmt_xdate()

fmt = '%1.2f'
cb = plt.colorbar(cax1,fraction=0.046, pad=0.04, format=fmt)
cb.update_ticks

fig.suptitle('2016 Monthly Pressure Data (no Normalization) $[mbar]$',fontsize=20, horizontalalignment='center')

fig.savefig('Pressure 2016 Full.jpeg', dpi=300)
plt.show()

有什么想法吗?

谢谢!

当坐标轴方面设置为 "equal" 时会出现此问题,这是 imshow 图的情况,并且添加了颜色条。

import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(5,5)
fig, ax = plt.subplots(figsize=(12, 3))
fig.patch.set_facecolor('#dbf4d9')

im = ax.imshow(x)

fig.colorbar(im)
plt.show()

解决方法是设置子图参数 leftright,使图像位于中心。这可能需要一些试验和错误,但工作如下:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(5,5)
fig, ax = plt.subplots(figsize=(12, 3))
plt.subplots_adjust(left=0.2, right=0.68)
fig.patch.set_facecolor('#dbf4d9')

im = ax.imshow(x)

fig.colorbar(im)
plt.show()

我无法使上述方法起作用;可能是因为我另外在PyQt5中绘图。

如果其他人在这里遇到困难,我最终在另一个 link 处使用公认的解决方案来解决这个问题 (Matplotlib 2 Subplots, 1 Colorbar)。只需为一个地块设置它,然后为该地块添加 cbar_ax。您仍然需要稍微调整一下数字。