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

问题描述:

我试图使用matplotlib绘制barchart。要绘制的项目数量可能会有所不同。我不能设置figure.set_size_inches(w,h)set_figwidth(w)常数(如6.,8或8.,12等),因为我不能提前知道w或h的值应该是什么。我想width of figure to increase as the number of items to be plotted increases。可以有人告诉我我怎么能做到这一点?根据x值的数量增加matplotlib中图的宽度

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

'len(地图)'应该给你条的数量,你知道这将进入函数。为什么不能根据此值设置图表的宽度?似乎你的例子中缺少一些东西。它应该是互动的吗? – Paul

+0

不,它不应该是交互式的......应该根据物品的数量计算宽度的缩放..这是我的braincells要睡觉的情况:-) – markjason72

则您可以在设置宽度初始化图:

# 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()线,你会得到你的要求的。

+0

非常感谢..很简单 – markjason72