Python 跳过条形图中的零值--Matplotlib

Python 跳过条形图中的零值--Matplotlib,python,matplotlib,bar-chart,Python,Matplotlib,Bar Chart,我有一个绘制自定义条形图的代码: def bar_chartQ2(sizes, colors, x_labels, c_labels, file_name): y, x = sizes.shape ind = np.arange(y)*8 width = 0.7 plt.figure() for i in range(x): plt.bar(ind + width*i, sizes[:, i], width, color=colors[i

我有一个绘制自定义条形图的代码:

def bar_chartQ2(sizes, colors, x_labels, c_labels, file_name):
    y, x = sizes.shape
    ind = np.arange(y)*8
    width = 0.7

    plt.figure()
    for i in range(x):
        plt.bar(ind + width*i, sizes[:, i], width, color=colors[i], label=c_labels[i])

c_labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'Unknown'] 
x_labels = ['1)', '2)', '3)', '4)', '5)']
sizes = np.array([[2, 8, 2, 1, 0, 0, 0, 0, 1],
                  [2, 4, 6, 0, 0, 0, 1, 0, 1],
                  [2, 0, 0, 2, 5, 0, 0, 1, 3],
                  [1, 0, 0, 3, 2, 2, 4, 0, 2],
                  [1, 0, 1, 0, 1, 1, 4, 3, 2]])
colors = ['royalblue', 'red', 'orange', 'green', 'purple', 'deepskyblue', 'deeppink', 'limegreen', 'firebrick']

bar_chartQ2(sizes, colors, x_labels, c_labels, 'Q2')
    plt.legend(loc=(1.2, 0.2), shadow=True)
    plt.xticks(ind + x/2.0*width, x_labels)

    plt.tight_layout()
    plt.savefig(file_name+'.pdf', format='pdf', bbox_inches='tight')
到目前为止,结果如下:

我觉得它有点不可读


我想跳过size==0的条,即防止同一项目的条之间出现空格。

这里有一个解决方案,可以将所有数据绘制在单独的轴上:

import numpy 
from matplotlib import pyplot
import seaborn

c_labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'Unknown'] 
colors = ['royalblue', 'red', 'orange', 'green', 'purple', 'deepskyblue', 'deeppink', 'limegreen', 'firebrick']
x_labels = ['1)', '2)', '3)', '4)', '5)']
sizes = numpy.array([
    [2, 8, 2, 1, 0, 0, 0, 0, 1],
    [2, 4, 6, 0, 0, 0, 1, 0, 1],
    [2, 0, 0, 2, 5, 0, 0, 1, 3],
    [1, 0, 0, 3, 2, 2, 4, 0, 2],
    [1, 0, 1, 0, 1, 1, 4, 3, 2]
])

fig, axes = pyplot.subplots(ncols=sizes.shape[0], figsize=(10, 5), sharey=True)
for ax, height, title in zip(axes, sizes, x_labels):
    ax.set_title(title)

    left = numpy.arange(len(height)) + 1
    ax.bar(left, height, color=colors)

    ax.set_xticks(left)
    ax.set_xticklabels(c_labels, rotation=45, rotation_mode='anchor', ha='right')

请注意:色盲的人怎么办?在cse中,这个职位仍然可以帮助他们理解结果。是的,你是对的,@WillemVanOnsem。但现在如何,你不认为很难识别集群吗?我的意思是,有5个问题,每个问题有8个选项。如果没有颜色,我无法识别每个问题对应的栏。也许用图案代替颜色会更好。或者其他一些方法。我建议您将每个簇绘制在它自己的轴上,然后标记每个条的位置。如何显示图例?我尝试了
handles,labels=axes[0]。获取\u legend\u handles\u labels()
然后是
plt.legend(handles,labels)
(在循环之外),但它根本没有出现……另外,当我使用
plt.tight\u layout()和`plt.savefig(file\u name+'.pdf',format='pdf',bbox inches='tight')保存此绘图时,所有文本都会消失。这种情况发生在这个
seaborn
软件包中。