带有颜色条和两个imshow的Matplotlib问题

bkhjykvo  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(157)

我想在一个图形上绘制2 imshow,但我只想让右边的子图形在其绘图的底部有颜色条。
这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

cm = 1/2.54
fig = plt.figure()
fig.set_size_inches(21*cm,29.7*cm)
gs = GridSpec(1,2,figure=fig)

data1 = np.random.rand(100,1000)
data2 = np.random.rand(100,1000)

ax_left = fig.add_subplot(gs[:,0])
img_left = ax_left.imshow(data1, aspect='auto')

ax_right = fig.add_subplot(gs[:,1])
img_right = ax_right.imshow(data2, aspect='auto')

fig.colorbar(img_right,ax = [ax_right], location='bottom')

plt.show()

正如你所看到的两个imshow是不一样的大小(我认为是因为颜色条)。你有什么想法有相同的数字,但与左一个相同的高度与右图(并保持颜色条为右imshow)。
先谢谢你

b1payxdu

b1payxdu1#

一种方法是在网格中添加第二行,并使用cax作为kwarg在右下角的网格中绘制颜色条:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

cm = 1/2.54
fig = plt.figure()
fig.set_size_inches(21*cm,29.7*cm)
gs = GridSpec(2,2,figure=fig, hspace=0.1, height_ratios=[20, 1]) # adjust hspace and height_ratios to your liking

data1 = np.random.rand(100,1000)
data2 = np.random.rand(100,1000)

ax_left = fig.add_subplot(gs[0,0])
img_left = ax_left.imshow(data1, aspect='auto')

ax_right = fig.add_subplot(gs[0,1])
img_right = ax_right.imshow(data2, aspect='auto')

ax_cb = fig.add_subplot(gs[1,1])
fig.colorbar(img_right, cax=ax_cb, orientation='horizontal')

plt.show()

输出:

相关问题