Export High Resolution Graphics in Python using Matplotlib pyplot.savefig Function

May. 25, 2024

In Python, we can use Matplotlib pyplot.savefig function1 to export graphics, and specify dpi (dots per inch)2 of the figure. Take the Matplotlib official example Bar color demo3 as an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_colors.html#sphx-glr-gallery-lines-bars-and-markers-bar-colors-py

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']

ax.bar(fruits, counts, label=bar_labels, color=bar_colors)

ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')

# Save the figure
plt.savefig("image.png",dpi=300)

# Show the figure
plt.show()

300 dpi (65 KB):

image

600 dpi (149 KB):

image

1800 dpi (665 KB):

image

Compared with the way of directly copying image (in Spyder software) by right clicking on the image and then choosing Copy Image (the result shows as follows), we can get a much clearer image by pyplot.savefig function:

image-20240525104951321

this feature is the same as in MATLAB.

However, it should be noted that, pyplot.savefig should be used BEFORE pyplot.show; if choose the opposite order:

1
2
3
4
5
6
7
# ...

# Show the figure
plt.show()

# Save the figure
plt.savefig("image.png",dpi=300)

the exported image is empty:

image

As described in Matplotlib documentation4, this is because pyplot.show function will close the figure:

“If you want an image file as well as a user interface window, use pyplot.savefig before pyplot.show. At the end of (a blocking) show() the figure is closed and thus unregistered from pyplot. Calling pyplot.savefig afterwards would save a new and thus empty figure. This limitation of command order does not apply if the show is non-blocking or if you keep a reference to the figure and use Figure.savefig.”


References