Save Plot to Image File Instead of Displaying It Using Matplotlib

Save plot to image file instead of displaying it using Matplotlib

When using matplotlib.pyplot.savefig, the file format can be specified by the extension:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

That gives a rasterized or vectorized output respectively.
In addition, there is sometimes undesirable whitespace around the image, which can be removed with:

plt.savefig('foo.png', bbox_inches='tight')

Note that if showing the plot, plt.show() should follow plt.savefig(); otherwise, the file image will be blank.

How to save figure in Matplotlib in Python

pyplot keeps track of the "current figure", and functions called on the library which require a figure operate on that, but you can also be more explicit by calling savefig() on the figure object.

as an example from https://pythonspot.com/matplotlib-save-figure-to-image-file/:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
#plt.show()

fig.savefig('plot.png')

Being explicit in this way should solve your issue.

For references to pyplot functions which operate on the "current figure" see: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.html

Saving Colorbar Plot as Image File

I figured it out. Not sure why this works and what I did earlier didn't work. I think it had something to do with how Jupyter notebook displays things. But anyways here's what I did:

plt.scatter(X,Y,c=Z, cmap='gnuplot2')
clb = plt.colorbar()
clb.set_label('label')
plt.savefig('name.jpg') #this saves all of what is shown below
plt.show()

Matplotlib .savefig results in empty image

You must save it writing plt.savefig('path.pdf') BUT before plt.show(). I think it will work. Tell me.

Save plot from matplotlib so that plot is centered

As said in the comments, you can use GridSpecs:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

#generate data
import numpy as np
Xm, Ym = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Zm = (1 - Xm/2 + Xm**5 + Ym**3) * np.exp(-Xm**2 - Ym**2)
levels = np.linspace(Zm.min(), Zm.max(), 7)

fig = plt.figure(figsize=(10,8))
#define subplot width ratios
gs = GridSpec(1, 3, width_ratios=[1, 20, 1])

#leave first axis gs[0] empty for symmetry
#add middle plot for contour
plt_ax = fig.add_subplot(gs[1])
cp = plt_ax.contourf(Xm, Ym, Zm, levels=levels)

#add colorbar
cbar_ax = fig.add_subplot(gs[2])
cbar = fig.colorbar(cp, cax=cbar_ax)

#fig.savefig('test.png')

plt.show()

Sample output:
Sample Image

Update
As you now introduced the problem of different figure sizes: The same logic can be applied to the height of the colorbar by creating a subGridSpec. If we want to ensure consistency in appearance for different figure size ratios, we have to take this into account while creating the GridSpecs.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec

#generate data
import numpy as np
Xm, Ym = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Zm = (1 - Xm/2 + Xm**5 + Ym**3) * np.exp(-Xm**2 - Ym**2)
levels = np.linspace(Zm.min(), Zm.max(), 7)

width = 20
height = 8
fig = plt.figure(figsize=(width, height))
#define subplot width ratios
gs_main = GridSpec(1, 3, width_ratios=[1, 2*width, 1], wspace=1/width)

#add middle plot for contour
plt_ax = fig.add_subplot(gs_main[1])
cp = plt_ax.contourf(Xm, Ym, Zm, levels=levels)

#add colorbar to middle subGridSpec on the right
gs_cbar = GridSpecFromSubplotSpec(3, 1, subplot_spec=gs_main[2], height_ratios=[1, 8, 1])
cbar_ax = fig.add_subplot(gs_cbar[1])
cbar = fig.colorbar(cp, cax=cbar_ax)

#fig.savefig('test.png')

plt.show()

This keeps the width of the colorbar, its distance from the main plot, and its relative height constant over a range of figure sizes.



Related Topics



Leave a reply



Submit