Reputation: 223
I need to add a pandas dataframe to a pdf and also should write some info about it in the pdf. I have successfully completed in writing a pandas dataframe to a pdf .
Below is my code:
fig,ax=plt.subplots(figsize=(20,10))
ax.axis('tight')
ax.axis('off')
the_table=ax.table(cellText=df.values,colLabels=df.columns,loc='center')
pp=PdfPages("foo.pdf")
pp.savefig(fig,bboc_inches='tight')
pp.close()
The output PDF has a dataframe printed on it.
What should I do to add some more informations on it which is not a dataframe ?(Eg:I want to add Headings,Informations on it which are sentences)
I want to convert to pdf using matplotlib/Fpdf. Using Fpdf I can add sentences but not a table . So I used matplotlib.
Please give me an idea on how to do that. Thanks a lot!
Upvotes: 1
Views: 1197
Reputation: 3472
You can place any text using plt.text
where the parameters x
and y
are the actual coordinates in the graph. To place a text correctly, first turn on the axes and then place the text(s), finally turn the axes off using plt.axis('off')
. I have attached a sample code below.
import numpy as np
import matplotlib.pyplot as plt
plt.axis('off')
data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[139361, 331509, 343164, 781380, 52269]]
columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]
values = np.arange(0, 2500, 500)
value_increment = 1000
n_rows = len(data)
index = np.arange(len(columns)) + 0.3
bar_width = 0.4
y_offset = np.zeros(len(columns))
cell_text = []
for row in range(n_rows):
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
plt.text(x=0.5, y=0.8, s="Text 1 here")
plt.text(x=0.2, y=0.9, s="Text 2 here")
# Add a table at the bottom of the axes
the_table = plt.table(cellText=cell_text,
rowLabels=rows,
colLabels=columns,
loc='center')
plt.show()
Upvotes: 2