Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to export to PDF a graph based on a Pandas dataframe in Matplotlib?
To export a graph based on a Pandas DataFrame to PDF format in Matplotlib, you can use the savefig() method with a .pdf extension. This creates a high-quality PDF file suitable for reports and presentations.
Basic PDF Export
Here's how to create a DataFrame plot and save it as PDF ?
import matplotlib.pyplot as plt
import pandas as pd
# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample DataFrame
df = pd.DataFrame([[2, 1, 4], [5, 2, 1], [4, 0, 1]],
columns=['col1', 'col2', 'col3'])
# Plot the DataFrame
df.plot()
# Save as PDF
plt.savefig('dataframe_plot.pdf')
plt.show()
PDF Export with Custom Settings
You can customize the PDF output with additional parameters ?
import matplotlib.pyplot as plt
import pandas as pd
# Create sample data
data = {
'Sales': [100, 150, 120, 180, 200],
'Marketing': [30, 45, 35, 50, 60],
'Operations': [70, 80, 65, 90, 95]
}
df = pd.DataFrame(data, index=['Q1', 'Q2', 'Q3', 'Q4', 'Q5'])
# Create the plot
ax = df.plot(kind='bar', figsize=(10, 6))
ax.set_title('Quarterly Performance Report')
ax.set_xlabel('Quarters')
ax.set_ylabel('Amount ($000)')
# Save as PDF with custom settings
plt.savefig('quarterly_report.pdf',
bbox_inches='tight',
dpi=300,
format='pdf')
plt.show()
Key Parameters for PDF Export
| Parameter | Description | Example Value |
|---|---|---|
bbox_inches |
Removes extra whitespace | 'tight' |
dpi |
Resolution for raster elements | 300 |
format |
Explicitly specify format | 'pdf' |
transparent |
Transparent background | True |
Multiple Plots in One PDF
To save multiple plots in a single PDF file, use PdfPages ?
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
# Create sample data
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'X': [7, 8, 9], 'Y': [10, 11, 12]})
# Save multiple plots to one PDF
with PdfPages('multi_page_report.pdf') as pdf:
# First plot
fig1, ax1 = plt.subplots()
df1.plot(ax=ax1)
ax1.set_title('Dataset 1')
pdf.savefig(fig1, bbox_inches='tight')
# Second plot
fig2, ax2 = plt.subplots()
df2.plot(ax=ax2)
ax2.set_title('Dataset 2')
pdf.savefig(fig2, bbox_inches='tight')
plt.close('all')
Output
When you execute the code, it will create a PDF file containing your DataFrame visualization:
Conclusion
Use plt.savefig('filename.pdf') to export DataFrame plots as PDF files. Include parameters like bbox_inches='tight' and dpi=300 for professional-quality output suitable for reports and presentations.
Advertisements
