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

时间:2019-07-03 09:10:15

标签: python matplotlib colorbar

这是我的代码,

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()

它会产生图像

enter image description here

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

enter image description here

有人可以帮助我解决这个问题吗?预先感谢您的任何有益建议!

2 个答案:

答案 0 :(得分:1)

不幸的是,

tight_layout对解决这个问题没有帮助。没有tight_layout也没有axes_grid可以正常工作:

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])
plt.show()

sharedcbar

如果您想获得更好的间距,可以尝试constrained_layout

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

Constrained_layout

受约束的布局也仅适用于一个轴:

fig.colorbar(mesh_2, ax=ax_2)

Oneaxes

答案 1 :(得分:0)

在@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()

它会产生

enter image description here