python - 跳过条形图中的零值——Matplotlib

标签 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 的条形,即防止同一项目的条形之间出现空白。

最佳答案

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

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

关于python - 跳过条形图中的零值——Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42725409/

相关文章:

python - 使用 Matplotlib、Python 的多个函数绘制为 1 个图形

python - 尝试使用 matplotlib 绘制 OpenCV 的 MSER 区域

ios - Coreplot iOS - 图表条之间的颜色空间

python - 在条形图上显示值

python magic 无法识别 unicode 文件名

python - sqlalchemy 创建一个整数列表作为子查询

python - pandas dataframe 对列进行排序会引发索引上的 keyerror

python - 在具有双 y 轴的 Matplotlib 图中在条形前面排列线条

reactjs - 使用 D3 可滚动 X 轴 React BarChart

python - 如何使用 native python 执行 ping 或 traceroute?