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:
Import matplotlib. To change the figure size, use figsize argument and set the width and the height of the plot. Next, we define the data coordinates. To plot a bar chart, use the bar() function. To display the chart, use the show() function.
Saving a plot on your disk as an image file Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.
To change the size of subplots in Matplotlib, use the plt. subplots() method with the figsize parameter (e.g., figsize=(8,6) ) to specify one size for all subplots — unit in inches — and the gridspec_kw parameter (e.g., gridspec_kw={'width_ratios': [2, 1]} ) to specify individual sizes.
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)
From the documentation, you can add a dpi
argument to set the resolution.
savefig('foo.png', dpi=199)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With