Customizing and saving matplotlib generated figures¶

Below, we show examples for customizing and saving figures generated by matplotlib

You may find plenty of other examples with source code on the matplotlib gallery https://matplotlib.org/stable/gallery/index.html

In [1]:
import numpy as np
import matplotlib.pyplot as plt
In [2]:
#Generate toy data
x = np.linspace(0,10);
y = x**2;
In [3]:
#Sets the font size used on the tick (number), and axes labels
plt.rc('font', size=12)
In [4]:
#Create a figure object f1. Note the argument for figsize. 
f1 = plt.figure(figsize = [8,3]);
plt.plot(x,y,'k.')
plt.xlabel('time(s)');
plt.ylabel('Signal (arb. units.)')
Out[4]:
Text(0, 0.5, 'Signal (arb. units.)')

The code below saves the figure as a pdf. The bbox_inches = 'tight' option ensures that the white space is trimmed.

In [5]:
#Save figure as a pdf, 
f1.savefig('fig1.pdf',bbox_inches='tight')
In [6]:
#Further customization
#Create a figure object f1. Note the argument for figsize. 
f2 = plt.figure(figsize = [4,3]);
plt.plot(x,y,'.')
# Vary the x label font size independent of the tick labels. 
plt.xlabel('time(s)', fontsize = 18); 
plt.ylabel('Signal (arb. units.)', fontsize = 8, color = 'red')
Out[6]:
Text(0, 0.5, 'Signal (arb. units.)')
In [7]:
#Save figure 2 as a pdf
f2.savefig('fig2.pdf',bbox_inches='tight')
In [ ]: