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踩坑:类与类对象类型参数传递与使用
前言 对初学者来说,Python确实简单好用,毕竟动态类型语言,不用定义就可以拿来用,类型之间随意转换简直不要太方便,因此Python用来写写小脚本,爬虫程序什么的,没什么问题。 不过,一旦用来开发稍微大型一点的项目,例如搭建一个Web应用,就会遇到一些问题,一般缺乏经验的人都会陷入某些坑中。= =... 坑 先说坑,函数参数类型是一坑,类与类的对象这又是一坑。 虽然之前用其他静态类型语言(例如C
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创建压缩文件
代码实现 # 创建一个目录来保存这些东西 temp_path = os.path.join(settings.MEDIA_ROOT, 'temp', str(uuid.uuid4())) os.makedirs(temp_path) # 创建压缩文件 archive_path = os.path.join(temp_path, 'archive.zip') with zipfile.ZipFile
2022-09-30 · Python · 约 1 分钟
Python接入企业微信推送信息到内部群里
前言 之前一篇文章提到了使用wechatpy库来实现企业微信应用登录:Django + Taro 前后端分离项目实现企业微信登录 其实这个库可以实现的功能非常多,基本微信开发涉及到的功能都能实现。 本文介绍一个很常用的场景:实时推送信息到企业微信群里。 安装 首先安装wechatpy库 pip install wechatpy 如果运行的时候提示需要安装其他库(比如加解密相关的)那就按照提示安装,
2022-04-08 · Python · 约 1 分钟
讨论
共 0 条加载评论中…