In today’s data visualization tutorial we’ll learn how to save a Matplotlib plot as a graphic file so you can later on embed into a website, presentation, Excel spreadsheet or documents.
Creating our Matplotlib chart
We’ll first go ahead and create our plot using Python and Matplotlib. Note that we’ll also use Numpy to generate the data for the plot.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace (1,25,25)
y = np.log(x)
fig, ax = plt.subplots()
ax.plot(x,y)
ax.set_title('Business trip cost')
ax.set_xlabel ('T')
ax.set_ylabel('$');
Saving your Matplotlib or Seaborn plot as a figure
Next is to go ahead and save our figure. We’ll now start by saving the chart as a graphical png file as shown below. We do that by passing the file name (fname parameter to the savefig method.
fig.savefig('business_trips.png')
Note that i just used the png format arbitrarily, i could have used jpeg, tif, jpg, svg and others.
Export multiple figures with savefig
If you have multiple figures you can call the savefig for each of them. If you have multiple plots for your figures, you can use the savefig command as shown below.
Export a Matplotlib graph as pdf
If we want to save the plot as a pdf file, we can easily tweak our code:
fig.savefig('business_trips.pdf')
Change the size and resolution of the saved plot
We are easily able to use the dpi parameter in order to pass the required resolution in dot per inch values.
fig.savefig('fig.png',dpi=100)
Savefig not working or blank
Key reason for savefig not exporting is that either you would like to export to a non supported format (such as html, mht , Excel, Word, PowerPoint) or that you are not setting up the correct file location in your operating system.
Putting it all together
FOr more tidy code, you might want to pass your arguments into the kwargs magic variable such as in the example below (note that we also modified the chart face color.
kwargs = dict(dpi=150, orientation = 'landscape', facecolor='grey')
fig.savefig('fig.jpeg',**kwargs)
And here’s our exported chart: