在条形图中跳过零值 - Matplotlib

时间:2017-03-10 18:30:47

标签: 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], 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')

到目前为止,这是结果:

enter image description here

我认为这有点难以理解。

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

1 个答案:

答案 0 :(得分:1)

这是一个在不同轴上绘制所有数据的解决方案:

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')

enter image description here