如何将颜色条添加到Matplotlib子图(不是子图)?

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

是否可以在子图中添加颜色条?我尝试了以下方法,但是得到了一个错误。
下面是示例代码:

from matplotlib import pyplot as plt
import numpy as np

a = np.array([np.random.randint(-2,5,10) for x in range(0,5)])

fig = plt.figure(figsize=(10,10))
subfigs = fig.subfigures(2,1, wspace=0.1)

axsTop = subfigs[0].subplots(1,1)
axsBot = subfigs[1].subplots(1,4)
axsTop.imshow(a)
subfigs[0].colorbar(a)
# subfigs[0].colorbar(a, ax=axsTop) # tried this, too
plt.show()
plt.close()

错误:属性错误:“numpy.ndarray”对象没有属性“get_array”

ktecyv1j

ktecyv1j1#

为了帮助其他人,我找到了一个使用nested gridspec而不是子图形的解决方案。颜色条连接到它自己的子图。我发现有3个垂直单位间隔0.1,1,0.2产生了一个更好的结果,为上图和颜色条相比,只有一个单一的;在这种情况下,色条子图比图像的色条子图高得多。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.patches import Polygon
from matplotlib.colorbar import Colorbar
import sys

a = np.array([np.random.randint(-2,5,10) for x in range(0,5)])

fig = plt.figure()
gs = gridspec.GridSpec(5,3, figure=fig, height_ratios=[0.1,1,0.2,1,1], width_ratios=[1,0.1,1])

ax1 = plt.subplot(gs[0:2,0])
plt1 = ax1.imshow(a)

cbax = plt.subplot(gs[0:2,1])
cb = Colorbar(ax=cbax, mappable=plt1)

ax2 = plt.subplot(gs[3,0])
x_vals = np.random.randint(0,10,10)
y_vals = np.random.randint(0,10,10)
ax2.scatter(x_vals, y_vals)

ax3 = plt.subplot(gs[3,2])
x_vals = np.random.randint(0,10,10)
y_vals = np.random.randint(0,10,10)
ax3.scatter(x_vals, y_vals)

ax4 = plt.subplot(gs[4,0])
x_vals = np.random.randint(0,10,10)
y_vals = np.random.randint(0,10,10)
ax4.scatter(x_vals, y_vals)

ax5 = plt.subplot(gs[4,2])
x_vals = np.random.randint(0,10,10)
y_vals = np.random.randint(0,10,10)
ax5.scatter(x_vals, y_vals)

plt.show()
plt.close()

Sample output image.

相关问题