ItGo.me Focus on IT Recommend

Home > python - matplotlib savefig() size control

python - matplotlib savefig() size control

2020腾讯云双十一活动,全年最低!!!(领取3500元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1074

【阿里云】双十一活动,全年抄底价,限时3天!(老用户也有),
入口地址https://www.aliyun.com/1111/home

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 + '\n' + 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:

python matplotlib pandas
|
  this question
edited Apr 24 '15 at 16:06 hitzg 5,200 9 27 asked Oct 25 '12 at 16:25 WonderSteve 172 2 3 12

 | 

4 Answers
4

From the documentation, you can add a dpi argument to set the resolution.

savefig('foo.png', dpi=199)

|
  this answer
edited Apr 24 '15 at 16:04 hitzg 5,200 9 27 answered Feb 3 '15 at 7:25 Xiaorong Liao 105 1 9

 | 

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

Recommend:python - Matplotlib savefig with a legend outside the plot

gend out of the plot code: import matplotlib.pyplot as pyplotx = [0, 1, 2, 3, 4]y = [xx*xx for xx in x]fig = pyplot.figure()ax = fig.add_subplot(111)box = ax.get_position()ax.set_position([box.x0, box.y0, box.width*0.8, box.height

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


|
  this answer
edited Jun 25 '14 at 4:41 answered Jun 25 '14 at 4:02 WHZW 45 1 8

 | 

The command pl.figure() makes a new matplotlib figure. The figure size is set at instantiation. You do want to set the figure size, but you already have a figure. So you were on the right track, but try this instead:

def drawHeatMap(df, city, province, collector, classtype, color, titleposy):
    try:
        fig = pl.figure(figsize=(....))
        ax = fig.add_subplot(111)
        ax.matshow(df.values, cmap='PuBuGn')
        pl.colorbar()
        aTitle = classtype + ' Composition Changes Over Time in ' + city + ', ' + province + '\n' + collector + ' collector. ' + 'rs100'
        ax.set_title(aTitle, x=0.5, y=titleposy, style='oblique', weight='bold')
        ax.set_xlabel('Collection Time')
        ax.set_xticks(range(len(df.columns)), df.columns, rotation=90)
        ax.set_yticks(range(len(df.index)), df.index)
        fileName = classtype + '-' + city + '-' + province + '-' + collector + '.png'
        fig.savefig(fileName)
    except ZeroDivisionError:
        errorMessage = 'No Data Available for ' + city + ', ' + province + ' with ' + collector + ' collector.'
        print errorMessage

|
  this answer
edited Feb 18 '13 at 18:31 G-Nugget 5,393 1 14 30 answered Oct 25 '12 at 17:04 Mr. Squig 1,783 9 10      I got AttributeError: 'NoneType' object has no attribute 'autoscale_None' –  WonderSteve Oct 25 '12 at 17:49      I changed the code so thePlot=ax.matshow(df.values, cmap='PuBuGn') pl.colorbar(thePlot, orientation='vertical) I got his with ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() –  WonderSteve Oct 25 '12 at 18:11      The attribute error should not have been caused by my changes to your code. The trace back should provide more information, but it looks like you're trying to access the autoscale_None attribute of some object. –  Mr. Squig Oct 26 '12 at 0:41

 | 

Short:
You just need to call pl.figure(figsize=...) before you call the pl.colorbar (and all the other stuff)

Explanation:
pl.figure creates a new figure (with given size), on which all pl.* methods will act in the following.
So pl.savefig just saves the last created figure, which is empty if you created a new one in the preceeding line.


|
  this answer
edited May 14 '13 at 15:41 hooy 5,425 1 21 41 answered Oct 25 '12 at 17:05 Maximilian 256 2 4      Calling matshow will create a figure, so he actually needs to call pl.figure() prior to matshow. –  Mr. Squig Oct 25 '12 at 17:10      I tried putting pl.figure(...) before pl.colorbar(). It seems to mess up my graph. I think it messed up matshow() somehow –  WonderSteve Oct 25 '12 at 17:47      I moved pl.figure() before matshow. What is interesting is...if I don't use show() and just savefig(). I will have my figures saved (still with stuff trimmed). If I called show() and savefig(). It will show my graphs and bunch of empty graphs –  WonderSteve Oct 25 '12 at 17:52      I put pl.figure() before matshow() Changing the figsize and dpi doesn't do anything to do the saved figure. –  WonderSteve Oct 25 '12 at 18:05      Could you upload an example of when it saves with the graph cut off? –  Mr. Squig Oct 25 '12 at 18:46  |  show more comments

Recommend:python - Is matplotlib savefig threadsafe

mputing jobs. After the processes are partitioned, they run their data loading and computation steps and then finish with a "save" step. Usually this involved writing data to database tables. But for a specific task, I need the output of ea

------splitte line----------------------------