返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Python

Python Data Display - Generating Table Images

Introduction The previous article introduced pushing messages to Enterprise WeChat groups. One of the projects pushed information as tables automatically generated with Python. This article explains how to generate table images with Python. Choosing a Suitable Library Python's greatest advantage is its rich collection of third-party libraries. Basically whatever feature you need, you can find a library someone else has already implemented, and you're done after calling it in a few lines of code. Pytable Project URL: https://github.com/HiroshiARAKI/pytable The first one I found was the Japanese-developed p

曦远 (DealiAxy)约 15 分钟
目录7 个章节

Introduction

The previous article introduced pushing messages to Enterprise WeChat groups. One of the projects pushed information as tables automatically generated with Python. This article explains how to generate table images with Python.

Choosing a Suitable Library

Python's greatest advantage is its rich collection of third-party libraries. Basically whatever feature you need, you can find a library someone else has already implemented, and you're done after calling it in a few lines of code.

Pytable

Project URL: https://github.com/HiroshiARAKI/pytable

The first one I found was the pytab library developed by a Japanese author. It draws tables based on matplotlib. With the default parameters, the generated tables look so-so, they cannot display Chinese characters, and the font is also very small, so the result is not ideal.

At first I still had a grind-it-out mindset and downloaded the library's source to hack it. After changing the font and size, the generated tables finally became presentable, but the layout still ran into all sorts of weird issues, like text overflowing cells. Exhausting...

Plotly

Official website: https://plotly.com/

Later I found a new library: plotly. The official site describes it as:

The front end for ML and data science models

A front-end visualization tool designed specifically for machine learning and data science; using it just to draw tables is a bit of overkill~ It renders via web pages. The examples looked decent, so I switched to this plotly to give it a try. Yep, it really works, so this is the one.

This article will introduce how to use both libraries, including the parts where I hacked pytab.

(Still, I recommend plotly—web rendering is just better)

pytab

First, install it

pip install pytab

Then I wrapped the table-drawing code into a function

import uuid
from typing import List, Dict, Optional, Tuple

import pytab

def draw_table(data: Dict[str, list]):
    """
    画表格

    :param data: 数据格式 {
        'a': [1.0, 2.1, 3.5, 4.0, 2.0, 1.0, 2.1, 3.5, 4.0, 2.0, ],
        'b': [5.7, 6.1, 7.2, 8.3, 1.2, 5.7, 6.1, 7.2, 8.3, 1.2, ],
        }
    :return:
    """
    # 设置字体,不然显示不了中文
    pytab.plt.rcParams["font.sans-serif"] = ["SimHei"]
    pytab.table( 
        data=data,
        data_loc='center',
        # th_type='dark',
        th_c='#aaaaee',  # 设置表头背景颜色
        td_c='gray',  # 设置数据行背景颜色
        table_type='striped',
        figsize=(len(data.keys()), int(len(data.values()) / len(data.keys()) + 1)),
        # fontsize=18,
    )

    # pytab.show()
    temp_file = os.path.join(tempfile.gettempdir(), f'{uuid.uuid4().hex}.jpg')
    print(temp_file)
    pytab.save(temp_file)
    return temp_file

Following this data format in the comments, a and b are the header column names, and the arrays after them are the data for each column. Easy to understand.

{
    'a': [1.0, 2.1, 3.5, 4.0, 2.0, 1.0, 2.1, 3.5, 4.0, 2.0, ],
    'b': [5.7, 6.1, 7.2, 8.3, 1.2, 5.7, 6.1, 7.2, 8.3, 1.2, ],
}

The table it draws looks like this

![image-20220409121840317](Python数据展示 - 生成表格图片.assets/image-20220409121840317.png)

Let's try how Chinese display turns out

{
    '列1': [1.0, 2.1, 3.5, 4.0, 2.0, 1.0, 2.1, 3.5, 4.0, 2.0, ],
    '列2': [5.7, 6.1, 7.2, 8.3, 1.2, 5.7, 6.1, 7.2, 8.3, 1.2, ],
}

It draws like this

![image-20220409131246284](Python数据展示 - 生成表格图片.assets/image-20220409131246284.png)

A bit ugly, right? Barely passable.

OK~ I won't fuss over pytab any further; after all, that's about its ceiling.

Next, let's look at plotly.

plotly

First, install it

pip install plotly

Without further ado, same as usual—I wrote it as a function again.

import uuid
from typing import List, Dict, Optional, Tuple

import plotly.graph_objects as go
import plotly.io as pio

def draw_table(headers: List[str], cells: List[list]):
    """
    画表

    :param headers: header=dict(values=['A Scores', 'B Scores'])
    :param cells: cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]])
    :return:
    """
    pio.kaleido.scope.default_width = len(','.join(headers)) * 20
    pio.kaleido.scope.default_height = 250 + len(cells[0]) * 20
    fig = go.Figure(data=[go.Table(header=dict(values=headers), cells=dict(values=cells))])
    # fig.show()
    image_file = os.path.join(tempfile.gettempdir(), f'{uuid.uuid4().hex}.jpg')
    print('write image to', image_file)
    fig.write_image(image_file)
    return image_file

This time the parameter format is different from pytab earlier. You need to pass two parameters, both of array type.

The first is the header; the second array is the cells.

Let's try an example first.

draw_table(['列A', '列B'], [[100, 90, 80, 90], [95, 85, 75, 95]])

Then uncomment fig.show() in the function code above, and you can see the generated table image.

After running it, you'll notice the browser opens automatically, because this library uses web pages to render tables. The result is as follows.

![image-20220409143239806](Python数据展示 - 生成表格图片.assets/image-20220409143239806.png)

The result is a bit better than pytab earlier, haha~

OK, that's it.

Next time I'll share some notes on recently developing a backend with Django.

References

_EOF_

Python Data Display - Generating Table Images

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

python实现解析markdown文档中的图片,并且保存到本地~

背景 前阵子简书好像说是凉了,搞得我有点小慌,毕竟我的大部分博客都是放在简书上面的,虽然简书提供了打包导出功能,但是只能导出文字,图片的话还是存在简书服务器上面,再加上我一直想要重新做一个个人博客,于是就有了这篇文章。 思路 首先是要解析markdown文档,然后获取到其中的所有图片,再把图片按md文件分好目录保存。 解析markdown文档 这里我用了misaka模块,据说是python的mar

2021-12-18 · Python · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…