具有多个颜色条的子图

我试图绘制一个带有4个子图和2个颜色条的图形 . 这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

from matplotlib import rcParams
rcParams["savefig.dpi"] = 100
rcParams["font.size"] = 18

x1 = np.linspace(100, 1000, 10)
y1 = np.linspace(10, 17, 10)
z1 = np.linspace(4, 18, 10)
t1 = np.linspace(-0.3, 0.4, 10)

fig, axes = plt.subplots(2, 2, sharey = True, figsize = (10, 10))

a0 = axes[0][0].scatter(x1, y1, s = 40, c = z1, marker = 'o')
cbar1 = fig.colorbar(a0)
axes[0][0].set_ylabel('y1')
axes[0][0].set_xlabel('x1')
axes[0][0].xaxis.set_major_locator(MaxNLocator(4))

a1 = axes[0][1].scatter(t1, y1, s = 40, c = z1, marker = 'o')
axes[0][1].xaxis.set_major_locator(MaxNLocator(4))
axes[0][1].set_xlabel('t1')
cbar1.ax.set_ylabel('z1', rotation = 270)

x2 = np.linspace(450, 900, 20)
y2 = np.linspace(11, 12.5, 20)
z2 = np.linspace(12, 60, 20)
t2 = np.linspace(-0.3, 0.4, 20)

a0 = axes[1][0].scatter(x2, y2, c = z2, marker = 'o')
cbar2 = fig.colorbar(a0)
axes[1][0].set_ylabel('y2')
axes[1][0].set_xlabel('x2')
axes[1][0].xaxis.set_major_locator(MaxNLocator(4))

a1 = axes[1][1].scatter(t2, y2, c = z2, marker = 'o')
axes[1][0].xaxis.set_major_locator(MaxNLocator(4))
axes[1][1].set_xlabel('t2')
cbar2.ax.set_ylabel('z2', rotation = 270)

plt.show()

这是图:
enter image description here

The thing I want to fix is:

颜色栏位于右侧的远端 . 我希望1个颜色条位于第一行的右侧,而另一个颜色条位于第二行的右侧(基本上,就在它的位置) .

我怎样才能做到这一点?谢谢!

回答(1)

2 years ago

您可以输入另一个参数来选择要绘制颜色条的轴 . 以下是代码中的更改:

cbar1 = fig.colorbar(a0, ax=axes[0][1])

cbar2 = fig.colorbar(a0, ax=axes[1][1])

哪个产生这个情节:

enter image description here