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
目录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:
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

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

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.

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
- Using prettytable in Python to output pretty tables: https://linuxops.org/blog/python/prettytable.html
- Plotly documentation on tables: https://plotly.com/python/table/
- Plotly documentation on exporting images: https://plotly.com/python/static-image-export/
- Generating images from table display data in Python: https://www.jianshu.com/p/3bfbf1bf0699
_EOF_
Python Data Display - Generating Table Images
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
Python:使用logging模块记录日志
先看看基本用法例子 # -*- coding: utf-8 -*- import logging import sys # 获取logger实例,如果参数为空则返回root logger logger = logging.getLogger(AppName) # 指定logger输出格式 formatter = logging.Formatter('%(asctime)s %(levelna
2022-05-27 · Python · 约 1 分钟
Python中的三元表达式
一般语言的三元表达式都是这种形式: result = statement ? true : false // For examle result = a b ? a : b Python中的三元表达式比较特殊,用下面这种形式 result = true if statement else false # For example result = a if a b else b
2022-05-27 · Python · 约 1 分钟
python实现解析markdown文档中的图片,并且保存到本地~
背景 前阵子简书好像说是凉了,搞得我有点小慌,毕竟我的大部分博客都是放在简书上面的,虽然简书提供了打包导出功能,但是只能导出文字,图片的话还是存在简书服务器上面,再加上我一直想要重新做一个个人博客,于是就有了这篇文章。 思路 首先是要解析markdown文档,然后获取到其中的所有图片,再把图片按md文件分好目录保存。 解析markdown文档 这里我用了misaka模块,据说是python的mar
2021-12-18 · Python · 约 1 分钟
Jupyter-Notebook-简单配置
安装主题 默认主题太丑了,必须换个好看的主题,pip安装: pip install jupyterthemes 装完之后: # 列出所有主题 jt -l # 设置主题 # -T 启用工具栏 # -N 启用名称栏 jt -t 主题名称 -T -N 自动补全 安装nbextensions pip install jupyter_contrib_nbextensions jupyter contrib
2021-12-18 · Python · 约 1 分钟
讨论
共 0 条加载评论中…