python - 使用 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。
请给我一个关于如何做到这一点的想法。非常感谢!
解决方案
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()
推荐阅读
- javascript - Getting an additional HTML data using xhttp in Django
- c# - .net - 选择中的异步/等待情况下的性能
- node.js - CucumberJS 和 Selenium Webdriver - 使用不同的输入运行相同的步骤
- python - DRF SerializerMethodField如何传递参数
- javascript - 关于标签的动态分组复选框列表
- mysql - 为什么我的查询在 sql 中的 Left Join 后不断重复字段
- machine-learning - 上传和标记照片对
- scala - Scala Spark:为范围创建列的最佳方法
- r - 在R中组合多个xtables
- pandas - AttributeError:模块“pandas”没有属性“read_excel”