Python PyG2Plot 原理与核心文件解析

陈默
陈默
发布时间:2026-10-14| 5人浏览过
原创

本文深入解析 Python 库 PyG2Plot 的工作原理,指出其借鉴 pyecharts 但基于 G2Plot 配置式结构更为简洁。详细说明了 plot.py、engine.py 及 templates 三大核心文件的作用,并展示了通过 render 生成 HTML 或在 Jupyter Notebook 中预览的具体代码示例与使用场景。

1、说明

PyG2Plot 的实现逻辑相对直观,其设计参考了 pyecharts 的思路。然而,由于蚂蚁金服的 G2Plot 严格遵循可视分析理论中的配置式结构,因此 PyG2Plot 在封装层面比 pyecharts 要简洁得多。

其基本运作机制是:通过 Python 语法暴露 API,当调用 render 方法时,生成最终的 G2Plot HTML 文本。针对不同运行环境,生成的 HTML 内容会有所差异。

2、核心文件

  • plot.py:包含了 PyG2Plot 几乎全部的 API 接口。
  • engine.py:负责提供 HTML 渲染能力,底层基于 jinjia2 模板引擎实现,代码量较少。
  • templates:包含所有 jinjia2 模板文件。关于模板的具体用法,可参考 jinjia2 官方文档,其说明非常详尽。

知识点扩展:

python中pyg2plot如何使用

1、渲染出完整的 HTML

该方式适用于以下场景:

服务端 HTML 直出的场景。

生成可交互的可视化分享链接。

嵌入 Excel 等工具的场景。


from pyg2plot import Plot
 
line = Plot("Line")
 
line.set_options({
 "data": [
  { "year": "1991", "value": 3 },
  { "year": "1992", "value": 4 },
  { "year": "1993", "value": 3.5 },
  { "year": "1994", "value": 5 },
  { "year": "1995", "value": 4.9 },
  { "year": "1996", "value": 6 },
  { "year": "1997", "value": 7 },
  { "year": "1998", "value": 9 },
  { "year": "1999", "value": 13 },
 ],
 "xField": "year",
 "yField": "value",
})
# 1. render html file named plot.html
line.render("plot.html")
# 2. render html string
line.render_html()

2、在 Jupyter notebook 中预览


from pyg2plot import Plot
line = Plot("Line")
line.set_options({
 "height": 400, # set a default height in jupyter preview
 "data": [
  { "year": "1991", "value": 3 },
  { "year": "1992", "value": 4 },
  { "year": "1993", "value": 3.5 },
  { "year": "1994", "value": 5 },
  { "year": "1995", "value": 4.9 },
  { "year": "1996", "value": 6 },
  { "year": "1997", "value": 7 },
  { "year": "1998", "value": 9 },
  { "year": "1999", "value": 13 },
 ],
 "xField": "year",
 "yField": "value",
})
line.render_notebook()

到此这篇关于python pyg2plot的原理知识点总结的文章就介绍到这了,更多相关python pyg2plot的原理内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。