首页 > 解决方案 > 使用 matplotlib 将文本添加到 PDF

问题描述

在此处输入图像描述我需要在 pdf 中添加一个 pandas 数据框,并且还应该在 pdf 中写一些关于它的信息。我已成功完成将 pandas 数据框写入 pdf 。

下面是我的代码:

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()

输出 PDF 上印有数据框。

我应该怎么做才能添加更多不是数据框的信息?(Eg:I want to add Headings,Informations on it which are sentences)

我想使用 matplotlib/Fpdf 转换为 pdf。使用 Fpdf 我可以添加句子但不能添加表格。所以我使用了matplotlib。

请给我一个关于如何做到这一点的想法。非常感谢!

标签: pythonpandasdataframematplotlib

解决方案


plt.text您可以使用where 参数放置任何文本,x并且y是图形中的实际坐标。要正确放置文本,首先打开坐标区,然后放置文本,最后使用 . 关闭坐标区plt.axis('off')。我在下面附上了一个示例代码。

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()

在此处输入图像描述


推荐阅读