我正在使用子图在一个图中创建多个水平堆叠的条形图:
fig, axs = plt.subplots(1, len(kwargs), figsize=figsize, frameon = False)
subplot = 0
for key, value in kwargs.items():
leftCordinate = 0
for i in range(len(value)): ##value=[10,15,20]
axs[subplot].barh([0], value[i], left = leftCordinate, color=colors[i])
leftCordinate += value[i]
axs[subplot].axis('off')
subplot += 1
问题是当len(kwargs)=1
时,出现以下错误:
Exception has occurred: TypeError
'AxesSubplot' object is not subscriptable
经过研究,我发现了以下3种解决方案:
fig, axs = plt.subplots(1, len(kwargs), figsize=figsize, frameon = False, squeeze = False)
axs = axs.T.flatten()
if type(axs)!=np.ndarray : # Happens if nrows=ncols=1
axs = np.array([[axs]])
我已经尝试了所有方法,但没有一种方法适合我。还有其他解决方案,还是我需要为特殊情况len(kwargs)=1
编写单独的代码?