根据x值数量增加matplotlib图形宽度

4 投票
1 回答
7268 浏览
提问于 2025-04-16 23:52

我在用 matplotlib 画一个 barchart(柱状图)。要画的项目数量是会变化的。我不能用固定的数字(比如 6.、8. 或 8.、12. 等)来设置 figure.set_size_inches(w,h)set_figwidth(w),因为我事先不知道宽度(w)或高度(h)应该是多少。我希望图的宽度能随着要画的项目数量的增加而增加。有人能告诉我该怎么做吗?

import pylab

def create_barchart(map):
    xvaluenames = map.keys()
    xvaluenames.sort()
    yvalues = map.values()
    max_yvalue = get_max_yvalue(yvalues)
    xdata = range(len(xvaluenames))
    ydata = [map[x] for x in xvaluenames]
    splitxdata = [x.split('-',1) for x in xvaluenames]
    xlabels = [x[0] for x in splitxdata]
    figure = pylab.figure()
    ax = figure.add_subplot(1,1,1)
    figsize = figure.get_size_inches()
    print 'figure size1=',figsize,'width=',figsize[0],'height=',figsize[1]
    barwidth = .25
    ystep =  max_yvalue/5
    pylab.grid(True)
    if xdata and ydata:
        ax.bar(xdata, ydata, width=barwidth,align='center',color='orange')
        ax.set_xlabel('xvalues',color='green')
        ax.set_ylabel('yvalues',color='green')
        ax.set_xticks(xdata)
        ax.set_xlim([min(xdata) - 0.5, max(xdata) + 0.5])
        ax.set_xticklabels(xlabels)
        ax.set_yticks(range(0,max_yvalue+ystep,ystep))
        ax.set_ylim(0,max(ydata)+ystep)
    figure.autofmt_xdate(rotation=30)
    figure.savefig('mybarplot',format="png")
    print 'figure size2=',figure.get_size_inches()
    pylab.show()

def get_max_yvalue(yvals):
    return max(yvals) if yvals else 0

如果我尝试用少量的项目,我得到的结果是

if __name__=='__main__':
    datamap = dict(mark=39,jim=40, simon=20,dan=33)    
    print datamap
    create_barchart(datamap)

plot of small set

但是如果我用更多的项目

datamap = dict(mark=39,jim=40, simon=20,dan=33) 
additional_values= dict(jon=34,ray=23,bert=45,kevin=35,ned=31,bran=11,tywin=56,tyrion=30,jaime=36,griffin=25,viserys=25)
datamap.update(additional_values)  
create_barchart(datamap)

plot of a larger set

这看起来很糟糕,我在想有没有办法根据要画的项目数量来增加图的宽度,同时保持两种情况下柱子的宽度相同。

1 个回答

5

你可以在创建图形的时候设置宽度:

# default scale is 1 in your original case, scales with other cases:
widthscale = len(yvalues)/4 
figsize = (8*widthscale,6) # fig size in inches (width,height)
figure = pylab.figure(figsize = figsize) # set the figsize

figure = pylab.figure() 这一行替换成上面的三行代码,你就能得到你想要的效果。

撰写回答