To create a matplotlib figure with defined dimensions, specify the size of the figure and its DPI (dots per inch). This ensures your saved figures have exactly the resolution that you need. Examples:
Save a figure of dimensions 600 * 600
To accomplish this, the best solution is to:
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 6))
x = [1,10]
y = [3,6]
plt.plot(x,y,'--')
plt.savefig('DashedLine_01.png', dpi=100, facecolor='white')
plt.show()
It will create a png image of dimensions 600 by 600. It is noteworthy that the dpi of a figure is specified only when it has been saved. The dots per inch (DPI) determines the resolution of an image and directly correlates to its size in bytes. As DPI increases, so does the file size.
Note: To ensure a successful video creation with ffmeg, it is critical that the width of the images can be equally divided by two (or you will get the error "ffmpeg : width not divisible by 2"). See How to create a video using a list of images with python ?
Another exaample
On the other hand, you can also define dpi in figure() to enhance image resolution without impacting its output. When used with plt.show(), it will result in a higher quality image display:
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 6), dpi=100,)
x = [1,10]
y = [3,6]
plt.plot(x,y,'--')
plt.savefig('DashedLine_01.png', facecolor='white')
plt.show()
Determine the optimal proportions between height and width
If you are having trouble balancing the proportions of your figure in terms of height and width, a solution is to save first the figure using bbox_inches='tight':
import matplotlib.pyplot as plt
x = [1,10]
y = [3,6]
plt.plot(x,y,'--')
plt.savefig('DashedLine_01.png', facecolor='white', bbox_inches='tight')
plt.show()
This code will generate a PNG image of dimensions 372.0 * 248.0, so the ratio is
372.0 / 248.0 = 1.5
is a good ratio for this figure. We can then for example use figsize=(12, 8) since 12 / 8 = 1.5:
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 8), dpi=100,)
x = [1,10]
y = [3,6]
plt.plot(x,y,'--')
plt.savefig('DashedLine_01.png', facecolor='white')
plt.show()