{"id":26686,"date":"2022-04-01T00:29:19","date_gmt":"2022-03-31T18:59:19","guid":{"rendered":"https:\/\/python-programs.com\/?p=26686"},"modified":"2022-04-01T00:29:19","modified_gmt":"2022-03-31T18:59:19","slug":"how-to-save-multiple-matplotlib-figures-in-single-pdf-file-in-python","status":"publish","type":"post","link":"https:\/\/python-programs.com\/how-to-save-multiple-matplotlib-figures-in-single-pdf-file-in-python\/","title":{"rendered":"How to Save Multiple matplotlib Figures in Single PDF File in Python?"},"content":{"rendered":"

In this article, we’ll learn how to save several plots in a single pdf file. In many scenarios, we need our output to be in a specific format, which we can easily acquire in Python by utilizing the following method.<\/p>\n

Let us take the demo.csv<\/strong> file as an example here to perform the task.<\/p>\n

\"Example<\/p>\n

Saving Multiple matplotlib Figures in Single PDF File in Python<\/h2>\n

1)Importing libraries<\/strong><\/p>\n

# Import pandas module using the import keyword\r\nimport pandas as pd\r\n# Import pyplot from matplotlib module using the import keyword\r\nfrom matplotlib import pyplot as pplot\r\n# Import seaborn module using the import keyword\r\nimport seaborn as sns\r\n<\/pre>\n

2)Reading a CSV File<\/strong><\/p>\n

# Pass some random CSV file to the read_csv() function of the pandas module \r\n# to read the given csv file\r\ngvn_datafrme = pd.read_csv(\"demo.csv\")<\/pre>\n

3)Displaying the first 5 rows of the CSV file<\/strong><\/p>\n

# Display the first 5 rows of the given csv file using the head() function\r\ngvn_datafrme.head()<\/pre>\n

Output:<\/strong><\/p>\n

\"First<\/p>\n

4)Plotting Multiple plots of a Given CSV File in a Single PDF File<\/strong><\/p>\n

# Passing some random plot size(width, length) to the figure() function\r\npplot.figure(figsize=(10, 4))\r\n# Plot the subplot by passing the arguments rows, columns and order of the plot to the \r\n# subplot() function\r\npplot.subplot(1, 2, 1)\r\n# Plot the graph of id, Salary columns in a given CSV file using the countplot() function\r\n# of the seaborn module\r\nsns.countplot('id', hue='Salary', data= gvn_datafrme)\r\npplot.subplot(1, 2, 2)\r\n# Plot the graph of id, Tax columns in a given CSV file using the countplot() function\r\n# of the seaborn module\r\n# Here we are plotting multiple plots in a single PDF file.\r\nsns.countplot('id', hue='Tax', data= gvn_datafrme)\r\n# Save the plots in a single PDF file by passing some random name to the savefig() function\r\npplot.savefig('Output.pdf')<\/pre>\n

Total Code<\/h2>\n

Approach:<\/strong><\/p>\n