Matplotlib save as pdf + 13 examples

In this Python tutorial, we will discuss Matplotlib save as pdf in python. Here we will cover different examples related to saving plot as pdf using matplotlib. And we will also cover the following topics:

  • Matplotlib save as pdf
  • Matplotlib savefig as pdf
  • Matplotlib savefig pdf example
  • Matplotlib savefig pdf dpi
  • Matplotlib save pdf transparent background
  • Matplotlib save graph as pdf
  • Matplotlib save subplot to pdf
  • Matplotlib savefig pdf cut off
  • Matplotlib save pdf file
  • Matplotlib savefig pdf multiple pages
  • Matplotlib save table as pdf
  • Matplotlib savefig pdf a4
  • Matplotlib savefig pdf empty

Matplotlib save as pdf

In this section, we are going to learn about how to save a plot or chart as a pdf file by using the matplotlib library. Firstly, we discuss what does “pdf” mean:

PDF stands for Portable Document Format

PDF format is used to save the files that can’t be modified. The biggest advantage of the PDF file is that it can be easily shared and printed.

The following steps are used to save a plot or graph as pdf are outlined below:

  • Defining Libraries: Import the important libraries which are required to save files as pdf and to define data (For data creation and manipulation: Numpy and Pandas, For data visualization: pyplot from matplotlib).
  • Define X and Y: Define the data values used for the x-axis and y-axis.
  • Create a pLot: By using plot(), scatter(), bar(), method you can create a plot or you can use any other method which ever you like.
  • Save as pdf: By using savefig() method you can save a file into your system. Set extension of the file to “pdf” as your main aim is to save as pdf.
  • Generate Plot: By using show() function, generate a plot to the user.

Matplotlib savefig as pdf

To export a graph with matplotlib as a pdf file we have to call the savefig() method. The main objective of this method is to save a graph to your local system memory.

The syntax of the savefig() method is as below:

matplotlib.pyplot.savefig(fname, dpi=None, 
                          facecolor='w',                                                
                          edgecolor='w',
                          orientation='portrait', 
                          papertype=None,                                  
                          format=None,                                
                          transparent=False,     
                          bbox_inches=None,                
                          pad_inches=0.1,                         
                          frameon=None,               
                          metadata=None)

The parameters used are discussed as below:

  • fname: specifies file name or file location.
  • dpi: specifies No.of dots per inch or picture quality.
  • facecolor: specifies the face color of the plot. By default, it is “White”.
  • edgecolor: specifies the edge color of the plot. By default, it is “White”.
  • orientation: specifies the orientation of the plot as Landscape or Portrait.
  • papertype: specifies the type of paper such as “letter”, “legal”, “a0 to a10”, etc.
  • format: specifies the extension of the file such as .pdf.
  • transparent: to make the background of the image transparent.
  • bbox_inches: specifies the portion of the plot to save. For a proper fitting set, it to “tight”.
  • pad_inches: specifies space around the plot.
  • metadata: specifies key/value pair to store in the plot metadata. Take data in the dictionary format.

Read Matplotlib plot a line

Matplotlib savefig pdf example

Let’s have a look at an example to understand the concept of saving a plot as a pdf file in matplotlib more clearly.

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data

x= [0, 1, 2, 3, 4, 5]
y= [1.5, 2, 3.6, 14, 2.5, 3.9]

# Plot 

plt.plot(x,y)

# Save as pdf

plt.savefig('save as pdf.pdf')

# Show image

plt.show() 
  • In the above example, we firstly import matplotlib.pyplot library. After that, we define data in x and y coordinates for plotting.
  • plot() method is used to plot a chart.
  • After this, we use the savefig() method to save plot figure in our project directory as a pdf file.
  • At last, we use the show() method to generate a plot for the user in a window.
matplotlib savefig pdf example
” Output of Plot save as a PDF file “

Read Python plot multiple lines using Matplotlib

Matplotlib savefig pdf dpi

The “dpi” argument decides the number of dots per inch. The dot’s values are defined in pixels.

The syntax is as given below:

matplotlib.pyplot.savefig(fname, dpi=None)

The arguments used are defined as below:

  • fname: Name of file or location.
  • dpi: specifies the quality of the plot.
READ:  How to attach an image in Turtle Python

Let’s see an example where we save the plot with dpi:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.arange(0, 12, 0.2)
y = np.sin(x)

# Plot figure

plt.plot(x, y)

# Save as pdf

plt.savefig('save as dpi .pdf', dpi=120, format='pdf', bbox_inches='tight')

# Generate Plot

plt.show()

Here we pass the dpi argument to the savefig() method and set its value 120.

matplotlib savefig pdf dpi
” Output of PDF with dpi “

Read What is matplotlib inline

Matplotlib save pdf transparent background

Here you will learn how to save files as a pdf with transparent background. You have to use a savefig() method to save a plot as a pdf file and pass an argument transparent and set its value to True.

Example:

The plot having green background color and you have to save it as a pdf file without a Transparent argument.

# Import Library

import matplotlib.pyplot as plt

# Define Data

student = [10, 5, 3, 2, 4]
weight = [35, 25, 20, 50, 43]

# Define background color

ax = plt.figure()
ax.set_facecolor('green')

# Plot Graph
  
plt.bar(weight,student) 

# Define axes label

plt.xlabel("Weight of the students")
plt.ylabel("Number of students")

# Save as pdf

plt.savefig('save pdf without transparent argument.pdf')

# Display Graph

plt.show() 

In the above example, we plot a bar graph and save it in system local memory by using the savefig() method.

To show you a difference here we set the background color to green.

matplotlib save pdf transparent background
” Pdf without Transparent argument “

Example:

The plot having green background color and you have to save the pdf file with the Transparent argument.

# Import Library

import matplotlib.pyplot as plt

# Define Data

student = [10, 5, 3, 2, 4]
weight = [35, 25, 20, 50, 43]

# Define background color

ax = plt.figure()
ax.set_facecolor('green')

# Plot Graph
  
plt.bar(weight,student) 

# Define axes label

plt.xlabel("Weight of the students")
plt.ylabel("Number of students")

# Save as pdf

plt.savefig('save pdf with transparent argument.pdf',transparent = True)

# Display Graph

plt.show() 

Here we pass the transparent as an argument to savefig() method and set its value to True.

matplotlib transparent background save pdf
” Output on user screen “
matplotlib save pdf having transparent background
” Output as PDF file with transparent background “

Read Matplotlib plot bar chart

Matplotlib save graph as pdf

Here we are going to learn how you can save bar graphs as a pdf file. For this firstly, you have to plot the bar chart and after that save it in pdf form.

The syntax is as below:

# Plot graph

matplotlib.pyplot.bar(x,y)

# Save as pdf

matplotlib.pyplot.savefig(fname)

Let’s see an example related to a bar chart save as a pdf file:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

subjects = ['MATHS', 'SCIENCE', 'ENGLISH', 'USA ENGLISH', 'SOCIAL-SCIENCE']
  
data = [20, 7, 31, 25, 12]

# Creating plot

plt.bar(subjects, data)

# save as pdf

plt.savefig('save graph as pdf.pdf')

# show plot

plt.show()

In the above example, we plot the bar chart by using the plt.bar() method and after that we use plt.savefig() method to save bar chart as a pdf file. So we set the extension to .pdf.

matplotlib save graph as pdf
” Output of graph save as PDF file “

Read Matplotlib subplot tutorial

Matplotlib save subplot to pdf

Here we will discuss how you can save subplots to a pdf file. By simply, using the savefig() method you can save it in a file. Take care of one thing, that you have to pass .pdf as an extension to the filename.

Let’s have a look at an example:

# Importing Libraries

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x1= [0, 1, 2, 3, 4, 5]
y1= [0, 1.5, 2.3, 6.5, 15, 2.6]

x2= [2, 4, 6, 8]
y2= [3, 6, 9, 12]

x3= [2.3, 5.6, 4.6, 9.36, 5.6]
y3= [10, 5, 4, 6, 2]

x4= [7, 8, 15]
y4= [6, 12, 18]

fig, ax = plt.subplots(2, 2)

# Set title

ax[0, 0].set_title("Plot 1")
ax[0, 1].set_title("Plot 2")
ax[1, 0].set_title("Plot 3")
ax[1, 1].set_title("Plot 4")


# Plot graph

ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)

# Save as pdf

plt.savefig('save subplot as pdf.pdf')

# Display Subplot

fig.tight_layout()
plt.show()
  • In the above example, we import important libraries such as matplotlib.pyplot and numpy.
  • After this we define data to draw subplots in a figure area.
  • Then we use set_title() method to set different titles for each of the subplot.
  • By using savefig() method we save subplots in a pdf file by passing extension .pdf to filename.
  • In last, we use tight_layout() method for auto adjustment of subplots and show() method to generate subplots on user screen.
matplotlib save subplot to pdf
” Subplots in Pdf File “

Read Matplotlib best fit line

Matplotlib savefig pdf cut off

When we save the plot into a pdf file we get an extra border or space along with the plot.

If you want to cut off the extra space pass the bbox_inches argument in the savefig() method and set its value to ‘tight’.

READ:  How to use Python While with Assignment[4 Examples]

Let’s have a look at examples:

Example: When we normally save a plot into pdf file

Code:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

subjects = ['MATHS', 'SCIENCE', 'ENGLISH', 'HINDI', 'SOCIAL-SCIENCE']
  
data = [20, 7, 31, 25, 12]

# Creating plot

plt.pie(data, labels = subjects)

# save as pdf

plt.savefig('save as pdf without cutoff.pdf')

# show plot

plt.show()

In the above example, we plot the pie chart by using the plt.pie() method, and then by using the plt.savefig() method we save the plot as a pdf file.

Output:

matplotlib savefig pdf cut off
” With extra spacing around the plot “

Example: When we save plot into pdf and also remove extra spacing

Code:

# Import Library


import matplotlib.pyplot as plt
import numpy as np

# Define Data


subjects = ['MATHS', 'SCIENCE', 'ENGLISH', 'HINDI', 'SOCIAL-SCIENCE']
  
data = [20, 7, 31, 25, 12]

# Creating plot

plt.pie(data, labels = subjects)

# save as pdf

plt.savefig('save as pdf with cutoff.pdf', bbox_inches='tight')

# show plot


plt.show()

In the above example, we plot the pie chart by using the plt.pie() method, and then by using the plt.savefig() method we save the plot as a pdf file.

We pass the bbox_inches as an argument and set its value to ‘tight’ to get cut off the plot.

Output:

matplotlib savefig pdf having cut off
” Cut off of plot “

Conclusion: When we use bbox_inches as an argument in the savefig() method we get cut off of the plot.

Read Matplotlib subplots_adjust

Matplotlib save pdf file

In matplotlib, the generated plot can be saved as a PDF file by using the savefig() method of PdfPages Class.

Firstly, you have to import the matplotlib library.

The syntax is as given below:

from matplotlib.backends.backend_pdf import PdfPages 

Next, you have to implement PdfPages

The syntax is as given below:

PdfPages(filename = None, keep_empty = True, metadata = None)

The above-used parameters are as given below:

  • filename: specifies the name and location of the file you want to save as.
  • keep_empty: It takes boolean values. If false, the empty PDF files delete automatically.
  • metadata: It takes data in the form of dictionary. It has information like Title, Author, Subjects, Keywords, etc.

In last, PdfPages creates objects of a class.

The following are the main functions used by class object:

  • get_pagecount(): This method returns the number of pages in pdf file.
  • close(): This method is used to close the object.
  • savefig(): This method is used to save a figure to the pdf file.

Note: Specify the format. As your main aim is pdf so use .pdf as an extension.

Let’s see an example to have a better understanding:

# Import Libraries

from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import matplotlib.pyplot as plt

# Define Data

X = np.arange(20)
Y = X**2

# PdfPages method


pp = PdfPages('save as pdf file in matplotlib.pdf')

# Plot graph

plt.plot(X,Y)

# Object of class


pp.savefig()  

# Close object

pp.close()
  • In this above example, we first import the PdfPages library.
  • PdfPages() method is used to save the plot as a pdf.
  • Next, we define data for plotting and use plt.plot() method to plot graph.
  • Then we define savefig() and close() as an object of the class
matplotlib save pdf file
” PdfPages() “

Read Matplotlib log log plot

Matplotlib savefig pdf multiple pages

If you want to save multiple plots in a single file, you have to use the savefig() method of the PdfPages class.

Let’s see an example of multiple pages pdf:

# Import Library

from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(10)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# PdfPages()

pdf = PdfPages('hi.pdf')

# Create function

def multiple_plot(X,Y):
    plt.figure()
    plt.clf()
    plt.plot(X,Y)
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    pdf.savefig()
    
# call function

multiple_plot(x,y1)
multiple_plot(x,y2)
multiple_plot(x,y3)

# class function

pdf.close()
  • In the above example, firstly we import important libraries PdfPages, numpy, and matplotlib.pyplot.
  • After this, we define data that is used for plotting, and by using the PdfPages() method we define the name of the file and set .pdf as an extension of the file.
  • We create user define function name as multiple_plot() and in this we define plot() method xlabel(), ylabel() method and savefig() method of the class object.
  • Then we call the user-defined function to plot multiple graphs and the close() method of the class object.
matplotlib savefig pdf multiple pages
” Output of Page 1 out of Page 3 “
matplotlib savefig pdf having multiple pages
” Output of Page 2 out Page 3 “
matplotlib savefig pdf consist multiple pages
” Output of Page 3 Out of Page 3 “

Here we save three different plots in a single pdf file instead of three separate files.

Read Matplotlib plot_date

Matplotlib save table as pdf

If you want to create a table in matplotlib and save it as a pdf file. You have to perform the following steps:

  • Import PdfPages, matplotlib.pyplot, and numpy libraries.
  • Define col_names and data.
  • Then set figsize by using plt.subplot() method and set the axis off to invisible the axes.
  • Next by using plt.table() method plot the table and pass the cellText, colLabels, loc, and, colLoc as an argument and set its value as data, col_names, center, and right respectively.
  • Then use PdfPages() method and pass the location of the file to save it as Pdf.
  • Then in the last call the savefig() and close() method of the class object.
READ:  Modulenotfounderror No Module Named 'keras.utils.vis_utils'

Example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# Define Data

col_names = ["Col-1", "Col-2", "Col-3", "Col-4", "Col-5", "Col-6"]
data = np.random.randint(100, size=(30,6))

# Plot table

fig, ax = plt.subplots(1, figsize=(10,10))
ax.axis('off')
table = plt.table(cellText=data, colLabels=col_names,loc='center',colLoc='right')

# save as Pdf

pdf = PdfPages('save table as pdf.pdf')
pdf.savefig()
pdf.close()
matplotlib save table as pdf
plt.table()

Read Matplotlib dashed line

Matplotlib save vector as pdf

Firstly we have to understand what does vector means and how we have to plot vector in matplotlib.

A vector is an object that has both magnitude and direction.

Graphically we can plot a vector as a line segment whose length represents its magnitude and the arrow indicates the direction of the vector.

In matplotlib to plot a vector field we have two methods which are described as follow:

By using the quiver() method we can plot vector:

matplotlib.pyplot.quiver(X,Y,U,V,**kw)

The parameters used above are given as below:

  • X and Y: specifies the location of the vector.
  • U and V: specifies the direction of the vector.

By using the streamplot() method we can plot vector:

matplotlib.pyplot.streamplot(X,Y,U,V,density=1,linewidth=none,color=None,**kw)

The parameters used above are given as below:

  • X and Y: specifies 1D array spaced grid.
  • U and V: specifies the velocity of each point.
  • Density: specifies no. of vector per area of the plot.
  • Linewidth: represent thickness.

Let’s see an example of vector as pdf:

# Import libraries


import numpy as np
import matplotlib.pyplot as plt
 
# Vector location

X = [7]
Y = [1]
 
# Directional vectors

U = [5] 
V = [3] 
 
# Creating plot

plt.quiver(X, Y, U, V)

# Save as pdf

plt.savefig('vector as pdf.pdf')
 
# Show plot

plt.show()
  • In the above example, we firstly import matplotlib.pyplot, and numpy library.
  • Then we define the Vector location and Direction of the vector.
  • By using plt.quiver() we plot a vector graph and we use the plt.savefig() method to save the generated plot into a pdf file.
matplotlib save vector as pdf
” Save vector as Pdf “

Read Matplotlib scatter marker

Matplotlib savefig pdf a4

If you want to save the plot on a4 size sheet you have to set the papertype to a4 size and pass it to the savefig() method.

Example:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = np.arange(0, 12, 0.2)
y = np.sin(x)

# Plot figure

plt.plot(x, y)

# Save image 

plt.savefig('save as pdf on a4 size paper.pdf', papertype='a4')

# Generate Plot

plt.show()

Here we pass the papertype argument to the savefig() method and set its value to a4.

Note: This papertype argument only works on editors having versions older than 3.3 otherwise, you will have a warning like below:

matplotlib savefig pdf a4
Warning

Read Matplotlib title font size

Matplotlib savefig pdf empty

Here we are going to discuss a very common issue that was faced by many new matplotlib learners.

The issue is that when a user plots a graph in matplotlib and tries to save it as a PDF file in their local system they get an empty file.

Let’s see an example where you find this issue:

# Import Library

import matplotlib.pyplot as plt

# Define Data

x= [0, 1, 2, 3, 4, 5]
y= [1.5, 2, 3.6, 14, 2.5, 3.9]

# Plot 

plt.scatter(x,y)

# Show plot

plt.show() 

# Save as pdf

plt.savefig('save as pdf.pdf')
  • In the above example, we firstly import matplotlib.pyplot library.
  • After this, we define data coordinates and use plt.scatter() method to draw a scatter plot.
  • After this we use plt.show() method to visualize the plot on the screen.
  • Finally, we use plt.savefig() method to save your plot as an image.
matplotlib savefig pdf empty
” Output on user screen “
matplotlib savefig empty pdf
” Output In Pdf File “

Instead of getting the plot in the Pdf file, we get an empty pdf.

Solution:

Now I tell you the solution to solve this problem. The solution is that you have to call plt.show() method after the plt.savefig() method.

Let’s have a look at a solution code:

# Import Library

import matplotlib.pyplot as plt

# Define Data

x= [0, 1, 2, 3, 4, 5]
y= [1.5, 2, 3.6, 14, 2.5, 3.9]

# Plot 

plt.scatter(x,y)

# Save as pdf

plt.savefig('Pdf file consist plot.pdf')

# Show plot

plt.show() 
matplotlib empty savefig pdf
Solution

You may like the following tutorials:

In this Python tutorial, we have discussed the “Matplotlib save as pdf” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib save as pdf
  • Matplotlib savefig as pdf
  • Matplotlib savefig pdf example
  • Matplotlib savefig pdf dpi
  • Matplotlib save pdf transparent background
  • Matplotlib save graph as pdf
  • Matplotlib save subplot to pdf
  • Matplotlib savefig pdf cut off
  • Matplotlib save pdf file
  • Matplotlib savefig pdf multiple pages
  • Matplotlib save table as pdf
  • Matplotlib savefig pdf a4
  • Matplotlib savefig pdf empty