Skip to content

Instantly share code, notes, and snippets.

@neelratanguria
Last active January 30, 2025 09:34
Show Gist options
  • Save neelratanguria/d9f647c1881598303a166b7790bfa5ab to your computer and use it in GitHub Desktop.
Save neelratanguria/d9f647c1881598303a166b7790bfa5ab to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import pandas as pd
# Sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
# Create a PDF file to save both the plot and the DataFrame
with PdfPages('combined_output.pdf') as pdf:
# --- First page: Matplotlib plot ---
fig, ax = plt.subplots(figsize=(8.27, 11.69)) # A4 size
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])
ax.set_title('Sample Matplotlib Plot')
pdf.savefig(fig) # Save the plot to the PDF
plt.close(fig) # Close the plot
# --- Second page: Pandas DataFrame table ---
fig, ax = plt.subplots(figsize=(8.27, 11.69)) # A4 size
ax.axis('off') # Hide axes
# Add DataFrame table to the plot
table = ax.table(cellText=df.values, colLabels=df.columns, loc='center')
pdf.savefig(fig) # Save the DataFrame table to the PDF
plt.close(fig) # Close the plot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment