2016-01-18 56 views
0

我使用此代碼從動態源生成條形圖問題,我有的是,當我有少於10條酒吧的寬度變化,它是沒有這裏同樣的佈局是代碼:蟒蛇matplotlib如何使固定寬度條形圖

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

回答

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

+0

你好當我Â嘗試你的代碼,我有以下錯誤: –

+0

entries.extend([( '',0)] *(10 - LEN(項))) AttributeError的: 'dict_items'對象沒有「擴展」屬性 –

+0

您使用的是什麼版本的Python?這已經在Python 2.7.9中測試 –