绘图上有多个颜色条

问题描述 投票:0回答:1

我正在尝试在一张图上绘制三个图。左边两个只是常规图,但右上角一个需要是带有三个附加颜色条的相关矩阵,但我似乎无法正确获取颜色条的大小。

我尝试使用网格规范和子网格规范,如下所示:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.colors import ListedColormap
import numpy as np

np.random.seed(123941)
data = np.random.rand(20, 20)

cmap_bm_type = ListedColormap(['mediumseagreen', 'greenyellow', 'darkorchid', 'plum'])

fig = plt.figure(figsize=[12, 8])
gs = gridspec.GridSpec(2, 2, figure=fig)
ax1 = fig.add_subplot(gs[0])
sgs = gs[1].subgridspec(2, 3, height_ratios=[0.95, 0.05],
                        width_ratios=[0.15, 0.70, 0.15],
                        wspace=0.05)
ax2 = fig.add_subplot(sgs[1])
ax2.imshow(data)
ax2.axis('off')
cbar_left = fig.add_subplot(sgs[0])
cbar_bottom = fig.add_subplot(sgs[2])
cbar_right = fig.add_subplot(sgs[4])
ax3 = fig.add_subplot(gs[2])

plt.show()

但我能得到的只是

任何人都可以帮助我如何使“cbar_bottom”与“ax2”宽度相同?

matplotlib colorbar matplotlib-gridspec
1个回答
0
投票

要使 cbar_bottom 与 ax2 宽度相同,您可以调整 subgridspec 参数为颜色条分配正确的空间。 subgridspec 中的宽度比例应与您想要与 cbar_bottom 匹配的 ax2 宽度比例相匹配。在您当前的设置中,您有三列,其比率为 [0.15, 0.70, 0.15],这意味着中心部分(放置 ax2 的位置)占据子网格总宽度的 70%。

以下是如何修改代码以使 cbar_bottom 具有与 ax2 相同的宽度:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.colors import ListedColormap
import numpy as np

np.random.seed(123941)
data = np.random.rand(20, 20)

cmap_bm_type = ListedColormap(['mediumseagreen', 'greenyellow', 'darkorchid', 
'plum'])

fig = plt.figure(figsize=[12, 8])

# Define a gridspec of 2 rows and 2 columns
gs = gridspec.GridSpec(2, 2, figure=fig)

ax1 = fig.add_subplot(gs[0, 0])  # Top-left plot
ax3 = fig.add_subplot(gs[1, 0])  # Bottom-left plot

# Create a subgridspec for the top-right area with 3 rows and 1 column
sgs = gs[0, 1].subgridspec(3, 1, height_ratios=[0.05, 0.9, 0.05], hspace=0.05)

ax2 = fig.add_subplot(sgs[1, 0])  # The main plot on the top-right
ax2.imshow(data, cmap=cmap_bm_type)  # Display the image
ax2.axis('off')  # Turn off the axis

# Add the colorbars in the correct places
cbar_top = fig.add_subplot(sgs[0, 0])  # Colorbar at the top
cbar_bottom = fig.add_subplot(sgs[2, 0])  # Colorbar at the bottom, same width         
as ax2

# Create the colorbar using the data from ax2's image
plt.colorbar(ax2.get_images()[0], cax=cbar_top, orientation='horizontal')
plt.colorbar(ax2.get_images()[0], cax=cbar_bottom, orientation='horizontal')

plt.show()

在此修改版本中,通过将 cbar_bottom 设置在 subgridspec 的同一列中,将它们定义为与 ax2 具有相同的宽度。设置高度比 [0.05, 0.9, 0.05] 为顶部和底部的颜色条提供较小的空间,为主图 ax2 提供较大的空间。

请根据您的数据和视觉喜好调整色图和其他参数。

© www.soinside.com 2019 - 2024. All rights reserved.