python matplotlib如何制作固定宽度条形图

时间:2016-01-18 10:53:12

标签: python matplotlib charts

我正在使用此代码从动态源生成条形图我遇到的问题是,当我有少于10条时,条形的宽度会发生变化,而且这里的代码布局不同:< / p>

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from  Processesing import dataProcess

def chartmak (dic) :
    z = 0

    D={}
    D=dic
    fig, ax = plt.subplots()
    n = len(D)
    ax.barh(range(n), D.values(), align='center', fc='#80d0f1', ec='w')
    ax.set_yticks(range(n))

    #this need more work to put the GB or the TB
    ax.set_yticklabels(['{:3d} GB'.format(e) for e in D.values()], color='gray')
    ax.tick_params(pad=10)
    for i, (label, val) in enumerate(D.items()):
        z+=1
        ax.annotate(label.title(), xy=(10, i), fontsize=12, va='center')
    for spine in ('top', 'right', 'bottom', 'left'):
        ax.spines[spine].set_visible(False)
    ax.xaxis.set_ticks([])
    ax.yaxis.set_tick_params(length=0)

    plt.gca().invert_yaxis()
    plt.savefig("test.png")
    plt.show()

1 个答案:

答案 0 :(得分:2)

如果小于10,您可以填写字典条目,如下所示:

import matplotlib.pyplot as plt

def chartmak(dic):
    entries = list(dic.items())

    if len(entries) < 10:
        entries.extend([('', 0)] * (10 - len(entries)))

    values = [v for l, v in entries]

    fig, ax = plt.subplots()
    n = len(entries)
    ax.barh(range(n), values, align='center', fc='#80d0f1', ec='w')
    ax.set_yticks(range(n))

    #this need more work to put the GB or the TB
    ax.set_yticklabels(['' if e == 0 else '{:3d} GB'.format(e) for e in values], color='gray')
    ax.tick_params(pad=10)

    for i, (label, val) in enumerate(entries):
        ax.annotate(label.title(), xy=(10, i), fontsize=12, va='center')

    for spine in ('top', 'right', 'bottom', 'left'):
        ax.spines[spine].set_visible(False)

    ax.xaxis.set_ticks([])
    ax.yaxis.set_tick_params(length=0)

    plt.gca().invert_yaxis()
    plt.show()


chartmak({'1': 10, '2':20, '3':30})
chartmak({'1': 10, '2':20, '3':30, '4':40, '5':80, '6':120, '7':100, '8':50, '9':30, '10':40})

这将显示以下输出:

v1

v2