通过matplotlib的子图进行迭代

时间:2020-02-21 12:48:00

标签: python python-3.x numpy matplotlib subplot

我正在使用子图在一个图中创建多个水平堆叠的条形图:

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种解决方案:

  1. fig, axs = plt.subplots(1, len(kwargs), figsize=figsize, frameon = False, squeeze = False)

  2. axs = axs.T.flatten()

  3. if type(axs)!=np.ndarray : # Happens if nrows=ncols=1

      axs = np.array([[axs]])
    

我已经尝试了所有方法,但没有一种方法适合我。还有其他解决方案,还是我需要为特殊情况len(kwargs)=1编写单独的代码?

0 个答案:

没有答案