简体   繁体   English

如何使用 python 将字典保存为 PDF 中的表格,并带有单元格着色?

[英]How to use python to save dict as a table in PDF with cell coloring?

I have a dict variable to summary the errors of my experiments, which is defined as below:我有一个 dict 变量来总结我的实验的错误,定义如下:

my_dict= {' ': ['A error', 'B Error', 'C Error', 'D Error'], 'lab1': [0.34, 0.23, 80, 0.79], 'lab2': [0.53, 0.38, 96, 1.25], 'lab3': [0.40, 0.27, 68, 0.93]}

Is there a way in Python to save the above dict as a table in PDF? Python 中有没有办法将上述字典保存为 PDF 中的表? Here, I hope to assign some thresholds to the values: if error value is larger than threshold, the cell is red, otherwise, it is green.在这里,我希望为这些值分配一些阈值:如果误差值大于阈值,则单元格为红色,否则为绿色。

For example, in the above table "my_dict", I hope to set different thresholds to different cells.比如上表“my_dict”中,我希望对不同的cell设置不同的阈值。 Could someone provide some guidance on that?有人可以提供一些指导吗?

disclaimer: I am the author of pText免责声明:我是pText的作者

You can use pText to create the PDF you described.您可以使用pText创建您描述的 PDF。 Let's start by creating an empty Document让我们从创建一个空的Document开始

    # create document
    pdf = Document()

    # add page
    page = Page()
    pdf.append_page(page)

We are going to use a layout-manager to determine where content needs to be.我们将使用布局管理器来确定内容需要放在哪里。 This is a lot easier than trying to figure out the PDF coordinate system ourselves.这比我们自己弄清楚 PDF 坐标系要容易得多。

    # set layout
    layout = SingleColumnLayout(page)

Next comes the fun part, actually working with your data:接下来是有趣的部分,实际使用您的数据:

    my_dict= {' ': ['A Error', 'B Error', 'C Error', 'D Error'],
              'lab1': [0.34, 0.23, 0.80, 0.79],
              'lab2': [0.53, 0.38, 0.96, 1.25],
              'lab3': [0.40, 0.27, 0.68, 0.93]}

I'm going to define a dictionary to map boundaries unto colors.我将定义一个字典到 map 边界到 colors。 You could easily change this piece of code to add more color, or change the colors.您可以轻松更改这段代码以添加更多颜色,或更改 colors。

    colors = {0: X11Color("Green"),
              0.25: X11Color("Yellow"),
              0.5: X11Color("Orange"),
              0.75: X11Color("Red")}

Next we create the Table接下来我们创建Table

    table = Table(number_of_rows=4, number_of_columns=5)

Now we can call add on the table.现在我们可以在桌子上调用add了。 Whenever we do, content is added at the current row (starting at the top row).每当我们这样做时,内容都会添加到当前行(从顶行开始)。 If the row is full, we will automatically go to the next row.如果该行已满,我们将自动 go 到下一行。

    table.add(Paragraph(" "))

Now we add all the headers (I made them bold):现在我们添加所有的标题(我把它们加粗了):

    for h in my_dict[" "]:
        table.add(Paragraph(text=h, font="Helvetica-Bold", font_size=Decimal(12)))

Next step is to actually add all your data to the Table :下一步是将所有数据实际添加到Table中:

    for name, row in [(k,v) for k,v in my_dict.items() if k != " "]:
        table.add(Paragraph(name))
        for v in row:
            c = X11Color("Green")
            for b,bc in colors.items():
                if v > b:
                    c = bc
            table.add(Paragraph(str(v),
                                font_color=c,
                                justification=Justification.CENTERED))

I am going to make the border on this Table a bit thinner than it would be by default:我要让这个Table上的边框比默认情况下更薄一点:

    # set border
    table.set_border_width_on_all_cells(Decimal(0.2))

I am also going to add a Paragraph at the start of the Page to give some context as to what the table represents:我还将在Page的开头添加一个Paragraph ,以提供有关表格所代表内容的一些上下文:

    # add to layout
    layout.add(Paragraph("This table contains all measurands for 3 lab-sessions."))

Now we add the Table to the Page现在我们将Table添加到Page

    layout.add(table)

Finally, we store the PDF:最后,我们存储 PDF:

    # attempt to store PDF
    with open("output.pdf", "wb") as in_file_handle:
        PDF.dumps(in_file_handle, pdf)

The final result looks like this (but you can play around with colors, fonts, etc)最终结果如下所示(但您可以使用 colors、fonts 等)

在此处输入图像描述

You could create a pandas dataframe and then display a seaborn heatmap:您可以创建 pandas dataframe 然后显示 seaborn 热图:

import seaborn as sns
import pandas as pd
from matplotlib import pyplot as plt

my_dict= {' ': ['A error', 'B Error', 'C Error', 'D Error'], 'lab1': [0.34, 0.23, 80, 0.79], 'lab2': [0.53, 0.38, 96, 1.25], 'lab3': [0.40, 0.27, 68, 0.93]}
df = pd.DataFrame(my_dict)
df.set_index(' ', inplace=True)
sns.heatmap(df.T, cmap='RdYlGn', annot=True, cbar_kws={'label':'Error value'})
plt.savefig('Errors.pdf')
plt.show()

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM