PyEcharts:百度 ECharts 在 Python 里的最佳打开方式

ECharts 是百度开源的 JS 图表库,国内用得非常多。PyEcharts 把它搬到了 Python 里——用 Python 语法写 ECharts 配置,生成 HTML 交互图表。

画出来的图可以直接嵌网页、放 PPT、做数据大屏。

安装

pip install pyecharts

基础柱状图

from pyecharts.charts import Bar
from pyecharts import options as opts

bar = (
    Bar()
    .add_xaxis(["手机", "电脑", "耳机", "平板", "手表"])
    .add_yaxis("Q1", [150, 120, 200, 80, 60])
    .add_yaxis("Q2", [180, 110, 220, 95, 75])
    .set_global_opts(
        title_opts=opts.TitleOpts(title="各产品季度销量"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        yaxis_opts=opts.AxisOpts(name="销量(台)"),
    )
)
bar.render("bar_chart.html")  # 生成 HTML

折线图

from pyecharts.charts import Line

months = ["1月", "2月", "3月", "4月", "5月", "6月"]
line = (
    Line()
    .add_xaxis(months)
    .add_yaxis("销售额", [120, 135, 158, 142, 175, 190],
               markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]))
    .add_yaxis("利润", [30, 38, 45, 40, 52, 60])
    .set_global_opts(
        title_opts=opts.TitleOpts(title="销售趋势"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
    )
)
line.render("line_chart.html")

饼图

from pyecharts.charts import Pie

data = [("手机", 35), ("电脑", 28), ("耳机", 20), ("平板", 12), ("其他", 5)]
pie = (
    Pie()
    .add("", data, radius=["40%", "70%"])  # 环形图
    .set_global_opts(title_opts=opts.TitleOpts(title="产品销量占比"))
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
)
pie.render("pie_chart.html")

radius=["40%", "70%"] 是环形图,radius="70%" 是实心饼图。

散点图

from pyecharts.charts import Scatter

np.random.seed(42)
x = list(np.random.normal(170, 8, 100))
y = list(np.random.normal(65, 10, 100))

scatter = (
    Scatter()
    .add_xaxis(x)
    .add_yaxis("", y, symbol_size=10)
    .set_global_opts(
        title_opts=opts.TitleOpts(title="身高体重散点图"),
        xaxis_opts=opts.AxisOpts(name="身高(cm)"),
        yaxis_opts=opts.AxisOpts(name="体重(kg)"),
    )
)
scatter.render("scatter_chart.html")

中国地图

from pyecharts.charts import Map

province_data = [
    ("广东", 120), ("江苏", 110), ("山东", 100), ("浙江", 95),
    ("河南", 85), ("四川", 80), ("湖北", 75), ("湖南", 70),
    ("福建", 65), ("上海", 60), ("北京", 55), ("河北", 50),
]

map_chart = (
    Map()
    .add("销售额", province_data, "china")
    .set_global_opts(
        title_opts=opts.TitleOpts(title="各省销售额分布"),
        visualmap_opts=opts.VisualMapOpts(max_=120, is_piecewise=True),
    )
)
map_chart.render("china_map.html")

仪表盘

from pyecharts.charts import Gauge

gauge = (
    Gauge()
    .add("完成率", [("目标", 78.5)],
         axisline_opts=opts.AxisLineOpts(
             linestyle_opts=opts.LineStyleOpts(
                 color=[(0.3, "#67e0e3"), (0.7, "#37a2da"), (1, "#fd666d")]
             )
         ))
    .set_global_opts(title_opts=opts.TitleOpts(title="KPI完成率"))
)
gauge.render("gauge.html")

Tab:多图联动

from pyecharts.charts import Tab, Bar, Line, Pie

bar = (
    Bar()
    .add_xaxis(["A", "B", "C"])
    .add_yaxis("销量", [10, 20, 15])
)

line = (
    Line()
    .add_xaxis(["1月", "2月", "3月"])
    .add_yaxis("趋势", [10, 20, 15])
)

pie = (
    Pie()
    .add("", [("A", 30), ("B", 45), ("C", 25)])
)

tab = Tab()
tab.add(bar, "柱状图")
tab.add(line, "折线图")
tab.add(pie, "饼图")
tab.render("dashboard.html")

Grid:图表叠加

from pyecharts.charts import Bar, Line, Grid

bar = (
    Bar()
    .add_xaxis(["1月", "2月", "3月", "4月", "5月", "6月"])
    .add_yaxis("销售额", [120, 135, 158, 142, 175, 190])
)

line = (
    Line()
    .add_xaxis(["1月", "2月", "3月", "4月", "5月", "6月"])
    .add_yaxis("增速(%)", [5, 12, 15, 8, 18, 22])
)

grid = (
    Grid()
    .add(bar, grid_opts=opts.GridOpts(pos_bottom="30%"))
    .add(line, grid_opts=opts.GridOpts(pos_top="75%"))
)
grid.render("combined.html")

在 Jupyter 中直接渲染

# 不需要 render,直接在 Notebook 显示
from pyecharts.globals import CurrentConfig, NotebookType
CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB

bar = Bar()...
bar.load_javascript()
bar.render_notebook()

实战:电商数据看板

from pyecharts.charts import Bar, Line, Pie, Map, Grid, Tab
import pandas as pd
import numpy as np

# 模拟数据
np.random.seed(2026)
provinces = ["广东", "江苏", "山东", "浙江", "河南", "四川", "湖北", "湖南", "福建", "北京", "上海"]
categories = ["手机", "电脑", "耳机", "平板"]

data = []
for p in provinces:
    for c in categories:
        data.append({"province": p, "category": c, "sales": np.random.randint(10, 80)})
df = pd.DataFrame(data)

monthly = pd.DataFrame({
    "month": [f"{i}月" for i in range(1, 13)],
    "sales": np.random.randint(800, 1500, 12),
    "orders": np.random.randint(2000, 5000, 12),
})

# Tab 面板
tab = Tab(page_title="电商销售看板")

# 1. 月度销售趋势
line = (
    Line()
    .add_xaxis(monthly["month"].tolist())
    .add_yaxis("销售额(万元)", monthly["sales"].tolist())
    .add_yaxis("订单数", monthly["orders"].tolist())
    .set_global_opts(title_opts=opts.TitleOpts(title="月度销售趋势"))
)
tab.add(line, "销售趋势")

# 2. 品类销售
by_cat = df.groupby("category")["sales"].sum()
bar = (
    Bar()
    .add_xaxis(by_cat.index.tolist())
    .add_yaxis("销售额", by_cat.values.tolist())
    .set_global_opts(title_opts=opts.TitleOpts(title="品类销售排行"))
)
tab.add(bar, "品类排行")

# 3. 地区分布
by_prov = df.groupby("province")["sales"].sum()
map_chart = (
    Map()
    .add("销售额", [(k, int(v)) for k, v in by_prov.items()], "china")
    .set_global_opts(
        title_opts=opts.TitleOpts(title="地区销售分布"),
        visualmap_opts=opts.VisualMapOpts(max_=200),
    )
)
tab.add(map_chart, "地区分布")

tab.render("ecommerce_dashboard.html")
print("看板已生成:ecommerce_dashboard.html")

新手常见坑

坑1:地图不显示

需要额外安装地图包:

pip install pyecharts echarts-countries-pypkg echarts-china-provinces-pypkg echarts-china-cities-pypkg

坑2:render 后文件空白

检查数据是否为空列表。PyEcharts 对空数据不会报错,生成的是空白图。

坑3:Jupyter 渲染报错

确认安装了 jupyterlab,并在 Notebook 开头运行:

from pyecharts.globals import CurrentConfig
CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB

写在最后

PyEcharts 的定位很清晰——写 Python 代码,产出 JS 图表。做数据中台、大屏展示、定期报告时特别好用。生成的 HTML 可以直接发给老板,浏览器打开就能看,不需要装任何环境。

下一篇聊时间序列分析——用 Pandas 处理日期数据,然后画趋势图。

更多推荐