Python pyecharts
Bar/line/pie charts, rendering to HTML, and embedding in a page.
Key Pointspyecharts generates standalone HTML with the ECharts runtime — perfect for static reports, not for real-time dashboards.
Install and First Chart
pyecharts wraps ECharts and outputs a self-contained HTML file — open it directly, no server needed.
Bash
pip install pyechartsPython
from pyecharts.charts import Bar
from pyecharts import options as opts
bar = (
Bar()
.add_xaxis(["Java", "Python", "Go", "Rust"])
.add_yaxis("教程数", [17, 32, 8, 8])
.set_global_opts(
title_opts=opts.TitleOpts(title="各语言教程数量"),
yaxis_opts=opts.AxisOpts(name="课数"),
)
)
bar.render("bar.html")
print("ok")Output
okLine and Pie
Lines suit time series; pies only work for part-to-whole with five or fewer slices.
Python
from pyecharts.charts import Line, Pie
from pyecharts import options as opts
line = (
Line()
.add_xaxis(["Mon", "Tue", "Wed", "Thu"])
.add_yaxis("PV", [120, 200, 150, 260], is_smooth=True)
.set_global_opts(title_opts=opts.TitleOpts(title="Weekly PV"))
)
line.render("line.html")
pie = (
Pie()
.add("", [("Java", 40), ("Python", 35), ("Go", 15), ("其他", 10)])
.set_global_opts(title_opts=opts.TitleOpts(title="语言占比"))
)
pie.render("pie.html")Embedding
render_embed() returns a <div> plus <script> you can paste into an existing page; render_notebook() is for Jupyter.
Python
html = bar.render_embed()
with open("report.html", "w", encoding="utf-8") as f:
f.write(f"<html><body>{html}</body></html>")The generated HTML inlines ~1MB of ECharts JS. For production, point
InitOpts at a CDN or export just the option JSON.安装与第一个图
pyecharts 是 ECharts 的 Python 封装,输出的是完整 HTML 文件,双击就能看,不需要起服务。
Bash
pip install pyechartsPython
from pyecharts.charts import Bar
from pyecharts import options as opts
bar = (
Bar()
.add_xaxis(["Java", "Python", "Go", "Rust"])
.add_yaxis("教程数", [17, 32, 8, 8])
.set_global_opts(
title_opts=opts.TitleOpts(title="各语言教程数量"),
yaxis_opts=opts.AxisOpts(name="课数"),
)
)
bar.render("bar.html")
print("ok")Output
ok折线与饼图
折线图适合时间序列,饼图只适合「占比且类别不超过 5 个」的场景 —— 类别一多就换成条形图。
Python
from pyecharts.charts import Line, Pie
from pyecharts import options as opts
line = (
Line()
.add_xaxis(["Mon", "Tue", "Wed", "Thu"])
.add_yaxis("PV", [120, 200, 150, 260], is_smooth=True)
.set_global_opts(title_opts=opts.TitleOpts(title="Weekly PV"))
)
line.render("line.html")
pie = (
Pie()
.add("", [("Java", 40), ("Python", 35), ("Go", 15), ("其他", 10)])
.set_global_opts(title_opts=opts.TitleOpts(title="语言占比"))
)
pie.render("pie.html")嵌入页面
render_embed() 返回一段 <div> + <script>,可以直接塞进现有 HTML;render_notebook() 用于 Jupyter。
Python
html = bar.render_embed()
with open("report.html", "w", encoding="utf-8") as f:
f.write(f"<html><body>{html}</body></html>")生成的 HTML 会内联 ECharts 的 JS(约 1MB)。要上生产请改用
InitOpts 指定 CDN,或只导出 option JSON 交给前端渲染。