matplotlib savefig() size control

前端 未结 5 701
执笔经年
执笔经年 2021-01-07 17:25

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

def drawHeatMap(df, city, province, collector, classtype, color, titlep         


        
相关标签:
5条回答
  • 2021-01-07 17:59

    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
    
    0 讨论(0)
  • 2021-01-07 18:10

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

    savefig('foo.png', dpi=199)
    
    0 讨论(0)
  • 2021-01-07 18:16

    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)

    0 讨论(0)
  • 2021-01-07 18:18

    before calling pl.savefig(fileName) do plt.tight_layout()

    0 讨论(0)
  • 2021-01-07 18:23

    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.

    0 讨论(0)
提交回复
热议问题