python matplotlib如何使固定宽度条ch

2024-03-29 11:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我用这段代码从一个动态源生成一个条形图。我遇到的问题是,当我的条形图少于10个时,条形图的宽度会发生变化,并且与布局不同,这里是代码:

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

Tags: the代码infromimportformatplotlibrange
1条回答
网友
1楼 · 发布于 2024-03-29 11:21:14

如果字典条目少于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

相关问题 更多 >