Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

python - matplotlib savefig() size control

I wrote a function that took a dataframe generated from Pandas and produce a heatmap:

def drawHeatMap(df, city, province, collector, classtype, color, titleposy):
    try:
        thePlot = pl.matshow(df.values, cmap='PuBuGn')
        pl.colorbar(thePlot, orientation='vertical')
        aTitle = (classtype + ' Composition Changes Over Time in ' + city + 
                ', ' + province + '
' + collector + ' collector. ' + 'rs100')
        pl.title(aTitle, x=0.5, y=titleposy, style='oblique', weight='bold')
        pl.xlabel('Collection Time')
        pl.xticks(range(len(df.columns)), df.columns, rotation=90)
        pl.yticks(range(len(df.index)), df.index)
        fileName = (classtype + '-' + city + '-' 
                + province + '-' + collector + '.png')
        pl.savefig(fileName)
    except ZeroDivisionError:
        errorMessage = ('No Data Avaiable for ' + city + ', ' + province + 
                ' with ' + collector + ' collector.')
        print errorMessage

The problem I am having is, savefig() would save figures with the axis and graphics trimmed. I have to use show(), maximize the graph and manually save the figure with the GUI button myself.

How can I fix my function so savefig() would save the graphs properly? I tried to put a line like this before pl.savefig() to control my figure:

       pl.figure(figsize=....) 

but I end up producing some empty graphs. What is the proper way to write a matplotlib function that give me full control on saving the figure?

Updated with Example of a problem figure: enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I added plt.tight_layout() before savefig(), and it solved the trimming issue I had. Maybe it will help yours as well.

EDIT: I also set the figure size at the begining rcParams['figure.figsize'] = 40, 12(you can set your own width and height)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...