python可视化,子图数据长度不同导致的barh绘图柱条宽度不同问题

在处理一个类似

[[12,3],[],[20]]

的二维数据进行可视化时,我发现长度为1的数据直接占据了整块子图,修改barh参数height也不起作用。

img


情况大致如图。

数据大致如图

img

后来我灵光一闪认为是不同长度的数据导致的问题,插入了一列空值来占位,但是长度为2的数据和长度为3的数据还是粗细不一致。

img

有没有什么办法能够让它的宽度固定呢?我用的是plt的barh函数来绘制子图的,宽度的参数都一致,不管用不用tight_layout宽度都不一样。。

我最理想的可视化效果如下图所示

img

求问有没有什么除了循环用fig.add_subplot的方法之外更好的解决方法?只能拼接的话能不能在空白处仍然用竖线连接起来呢?

绘图函数源码如下

def show_graph(x_bottom, x, total_title, g_title, total_number, number_of_columns, time_list, percentage_list, sheet_name):
    # Subplots are organized in a rows * cols Grid
    # Tot and Cols are known
    cols = number_of_columns
    # Compute Rows required
    rows = total_number // cols
    rows += total_number % cols
    # Create a Position index
    position = range(1, total_number + 1)
    # Create main figure
    fig = plt.figure(figsize=(15, total_number * 4 + 3))
    plt.axis('off')
    for k in range(total_number):
        # add every single subplot to the figure with a for loop
        ax = fig.add_subplot(rows, cols, position[k])
        if len(x[k]) != 0:
            if len(x[k]) == 1:
                x[k] = x[k] + [0]
                x_bottom[k] = x_bottom[k] + ['Only one user']
            plt.barh(x_bottom[k], x[k], 0.5, facecolor='tan', alpha=0.6, left=0.1)
            plt.yticks(fontsize=15)
            index = np.arange(len(x_bottom[k]))
            for a, b in zip(index, x[k]):
                if b == 0:
                    ax.set_title(g_title[k] + '\nIt\'s total time is ' + time_list[k] +
                                 '.\nThe occurrence rate of issue devices is ' + str(percentage_list[k] * 100) + '%',
                                 x=0.5, y=0.5, fontsize=15)
                    continue
                else:
                    ax.set_title(g_title[k] + '\nIt\'s total time is ' + time_list[k] +
                                 '.\nThe occurrence rate of issue devices is ' + str(percentage_list[k] * 100) + '%',
                                 fontsize=15)
                    ax.text(b + 5, a - 0.01, '%.2f' % b + '%', ha='center', fontsize=15)
                ax.spines['top'].set_visible(False)
                ax.tick_params(direction='out', length=6,
                               grid_color='r', grid_alpha=0.5)
                plt.xlim(0, 100)
        else:
            plt.xlim(0, 100)
            ax.set_title('No log effects wake lock ' + g_title[k] + '.\nIt\'s total time is ' + time_list[k] + '.'
                         , x=0.5, y=0.5, fontsize=20)
            ax.axes.yaxis.set_visible(False)
            continue
        if k == total_number - 1:
            continue
        else:
            ax.axes.xaxis.set_visible(False)
            ax.spines['bottom'].set_visible(False)
    fig.suptitle(total_title, fontsize=20)
    plt.savefig(sheet_name + '.png', bbox_inches='tight')