温馨提示:本文翻译自stackoverflow.com,查看原文请点击:matplotlib - In python, how to correctly use `colorbar` and `pcolormesh`?

matplotlib - 在python中,如何正确使用`colorbar`和`pcolormesh`?

发布于 2020-03-27 11:45:41

这是我的代码,

from mpl_toolkits.axes_grid1 import make_axes_locatable # colorbar
from matplotlib import pyplot as plt
from matplotlib import cm # 3D surface color
import numpy as np
data1 = np.random.rand(10, 12)
data2 = np.random.rand(10, 12)
data3 = data1 - data2

vmin = min([data1.min(), data2.min(), data3.min()])
vmax = max([data1.max(), data2.max(), data2.max()])
fig, (ax_1, ax_2, ax_error) = plt.subplots(nrows=3, ncols=1, figsize=(6, 6))

ax_1.set_ylabel('x')
mesh_1 = ax_1.pcolormesh(data1.T, cmap = cm.coolwarm)

ax_2.set_ylabel('x')
mesh_2 = ax_2.pcolormesh(data2.T, cmap = cm.coolwarm)

mesh_error = ax_error.pcolormesh(data3.T, cmap = cm.coolwarm)
ax_error.set_ylabel('x')
ax_error.set_xlabel('t')

divider = make_axes_locatable(ax_2)
cax_val = divider.append_axes("right", size="2%", pad=.1)

fig.colorbar(mesh_2, ax=[ax_1, ax_2, ax_error], cax=cax_val)
fig.tight_layout()

plt.show()

并产生图像

在此处输入图片说明

但是,我期望它会产生下面的图片

在此处输入图片说明

谁能帮我解决这个问题?在此先感谢您提供任何有用的建议!

查看更多

查看更多

提问者
guorui
被浏览
49
guorui 2019-07-04 09:05

在@JodyKlymak的帮助下,我终于解决了这个问题。关键在于使用shrink,即fig.colorbar(mesh_2, ax=[ax_1, ax_2, ax_error], shrink=0.3)这是解决方案

from matplotlib import pyplot as plt
from matplotlib import cm # 3D surface color
import numpy as np
data1 = np.random.rand(10, 12)
data2 = np.random.rand(10, 12)
data3 = data1 - data2

fig, (ax_1, ax_2, ax_error) = plt.subplots(nrows=3, ncols=1, figsize=(6, 6))

mesh_1 = ax_1.pcolormesh(data1.T, cmap = cm.coolwarm)
mesh_2 = ax_2.pcolormesh(data2.T, cmap = cm.coolwarm)
mesh_error = ax_error.pcolormesh(data3.T, cmap = cm.coolwarm)

fig.colorbar(mesh_2, ax=[ax_1, ax_2, ax_error], shrink=0.3)
plt.show()

它产生

在此处输入图片说明