【Web开发】Python实现Web图表功能(pyecharts入门学习)

时间:2022-11-03 14:00:03

<font color=purple face=华文行楷 size="5">"柳丝榆荚自芳菲,不管桃飘与李飞;"

1、简介

A Python Echarts Plotting Library. Apache Echarts 是一个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而 Python 是一门富有表达力的语言,很适合用于数据处理。当数据分析遇上数据可视化时,pyecharts 诞生了。

【Web开发】Python实现Web图表功能(pyecharts入门学习)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

  • 简洁的 API 设计,使用如丝滑般流畅,支持链式调用
  • 囊括了 30+ 种常见图表,应有尽有
  • 支持主流 Notebook 环境,Jupyter Notebook 和 JupyterLab
  • 可轻松集成至 Flask,Sanic,Django 等主流 Web 框架
  • 高度灵活的配置项,可轻松搭配出精美的图表
  • 详细的文档和示例,帮助开发者更快的上手项目
  • 多达 400+ 地图文件,并且支持原生百度地图,为地理数据可视化提供强有力的支持 【Web开发】Python实现Web图表功能(pyecharts入门学习)

2、下载和安装

<font color=blue> 新版本系列将从 v1.0.0 开始,文档位于 pyecharts.org;示例位于 gallery.pyecharts.org

2.1 pip 安装

# 安装 v1 以上版本
$ pip install pyecharts -U

# 如果需要安装 0.5.11 版本的开发者,可以使用
# pip install pyecharts==0.5.11

2.2 源码安装

# 安装 v1 以上版本
$ git clone https://github.com/pyecharts/pyecharts.git
# 如果需要安装 0.5.11 版本,请使用 git clone https://github.com/pyecharts/pyecharts.git -b v05x
$ cd pyecharts
$ pip install -r requirements.txt
$ python setup.py install

【Web开发】Python实现Web图表功能(pyecharts入门学习)

3、快速入门

3.1 生成 HTML(本地环境)

  • 例子1:app.py
from pyecharts.charts import Bar
from pyecharts import options as opts

# V1 版本开始支持链式调用
bar = (
    Bar()
    .add_xaxis(["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"])
    .add_yaxis("商家A", [114, 55, 27, 101, 125, 27, 105])
    .add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49])
    .set_global_opts(title_opts=opts.TitleOpts(title="某商场销售情况(爱看书的小沐)"))
)
bar.render()

# 不习惯链式调用的开发者依旧可以单独调用方法
bar = Bar()
bar.add_xaxis(["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"])
bar.add_yaxis("商家A", [114, 55, 27, 101, 125, 27, 105])
bar.add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49])
bar.set_global_opts(title_opts=opts.TitleOpts(title="某商场销售情况(爱看书的小沐)"))
bar.render()

【Web开发】Python实现Web图表功能(pyecharts入门学习)

  • 例子2:app2.py
import random

from pyecharts import options as opts
from pyecharts.charts import Bar3D
from pyecharts.faker import Faker


data = [(i, j, random.randint(0, 12)) for i in range(6) for j in range(24)]
c = (
    Bar3D()
    .add(
        "",
        [[d[1], d[0], d[2]] for d in data],
        xaxis3d_opts=opts.Axis3DOpts(Faker.clock, type_="category"),
        yaxis3d_opts=opts.Axis3DOpts(Faker.week_en, type_="category"),
        zaxis3d_opts=opts.Axis3DOpts(type_="value"),
    )
    .set_global_opts(
        visualmap_opts=opts.VisualMapOpts(max_=20),
        title_opts=opts.TitleOpts(title="Bar3D-基本示例 (爱看书的小沐)"),
    )
    .render("bar3d_base.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

3.2 生成图片(本地环境)

  • 例子1:app.py
from snapshot_selenium import snapshot as driver

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


def bar_chart() -> Bar:
    c = (
        Bar()
        .add_xaxis(["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"])
        .add_yaxis("商家A", [114, 55, 27, 101, 125, 27, 105])
        .add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49])
        .reversal_axis()
        .set_series_opts(label_opts=opts.LabelOpts(position="right"))
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar-测试渲染图片(爱看书的小沐)"))
    )
    return c

# 需要安装 snapshot-selenium 或者 snapshot-phantomjs
make_snapshot(driver, bar_chart().render(), "bar.png")

【Web开发】Python实现Web图表功能(pyecharts入门学习)

  • 例子2:app2.py
from snapshot_selenium import snapshot as driver
from pyecharts.render import make_snapshot
from pyecharts import options as opts
from pyecharts.charts import Bar3D
import random

x_data = y_data = list(range(10))

def generate_data():
    data = []
    for j in range(10):
        for k in range(10):
            value = random.randint(0, 9)
            data.append([j, k, value * 2 + 4])
    return data

def bar3d_chart() -> Bar3D:
    
    bar3d = Bar3D()
    for _ in range(10):
        bar3d.add(
            "",
            generate_data(),
            shading="lambert",
            xaxis3d_opts=opts.Axis3DOpts(data=x_data, type_="value"),
            yaxis3d_opts=opts.Axis3DOpts(data=y_data, type_="value"),
            zaxis3d_opts=opts.Axis3DOpts(type_="value"),
        )

    bar3d.set_global_opts(title_opts=opts.TitleOpts("Bar3D-堆叠柱状图示例(爱看书的小沐)"))
    bar3d.set_series_opts(**{"stack": "stack"})
    # bar3d.render("bar3d_stack.html")
    return bar3d

# 需要安装 snapshot-selenium 或者 snapshot-phantomjs
make_snapshot(driver, bar3d_chart().render(), "bar3d.png")

【Web开发】Python实现Web图表功能(pyecharts入门学习)

3.3 Jupyter Notebook(Notebook 环境)

https://jupyter.org/try-jupyter/retro/notebooks/?path=notebooks/Intro.ipynb https://jupyter.org/install

  • 什么是Jupyter Notebook? ① Jupyter Notebook是基于网页的用于交互计算的应用程序。其可被应用于全过程计算:开发、文档编写、运行代码和展示结果。 ② Jupyter Notebook是以网页的形式打开,可以在网页页面中直接编写代码和运行代码,代码的运行结果也会直接在代码块下显示的程序。如在编程过程中需要编写说明文档,可在同一个页面中直接编写,便于作及时的说明和解释。

  • Jupyter Notebook的主要特点 ① 编程时具有语法高亮、缩进、tab补全的功能。 ② 可直接通过浏览器运行代码,同时在代码块下方展示运行结果。 ③ 以富媒体格式展示计算结果。富媒体格式包括:HTML,LaTeX,PNG,SVG等。 ④ 对代码编写说明文档或语句时,支持Markdown语法。 ⑤ 支持使用LaTeX编写数学性说明。 【Web开发】Python实现Web图表功能(pyecharts入门学习) Install the classic Jupyter Notebook with:

pip install notebook
jupyter notebook

【Web开发】Python实现Web图表功能(pyecharts入门学习)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

# How do I open a specific Notebook?
jupyter notebook notebook.ipynb

# How do I start the Notebook using a custom IP or port?
jupyter notebook --port 9999

# How do I start the Notebook server without opening a browser?
jupyter notebook --no-browser

# How do I get help about Notebook server options?
jupyter notebook --help

# Running a notebook is this easy.
jupyter run notebook.ipynb

# You can pass more than one notebook as well.
jupyter run notebook.ipynb notebook2.ipynb

# By default, notebook errors will be raised and printed into the terminal. You can suppress them by passing the --allow-errors flag.
jupyter run notebook.ipynb --allow-errors

编辑代码: 【Web开发】Python实现Web图表功能(pyecharts入门学习) 预览成果: 【Web开发】Python实现Web图表功能(pyecharts入门学习)

3.4 JupyterLab(Notebook 环境)

Install JupyterLab with pip:

pip install jupyterlab

【Web开发】Python实现Web图表功能(pyecharts入门学习) Once installed, launch JupyterLab with:

jupyter-lab

【Web开发】Python实现Web图表功能(pyecharts入门学习)【Web开发】Python实现Web图表功能(pyecharts入门学习) 鼠标点击NoteBook按钮,进入编辑界面,并输入代码如下如下: 【Web开发】Python实现Web图表功能(pyecharts入门学习)【Web开发】Python实现Web图表功能(pyecharts入门学习)

3.5 Voilà(Notebook 环境)

# Install Voilà with:
pip install voila

# Once installed, launch Voilà with:
voila

【Web开发】Python实现Web图表功能(pyecharts入门学习) 浏览器访问:http://localhost:8866/ 【Web开发】Python实现Web图表功能(pyecharts入门学习) 查看某个ipynb文件如下: 【Web开发】Python实现Web图表功能(pyecharts入门学习)

4、地图 Map

4.1 Map_base

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

c = (
    Map()
    .add("商家A", [list(z) for z in zip(Faker.provinces, Faker.values())], "china")
    .set_global_opts(title_opts=opts.TitleOpts(title="Map-基本示例"))
    .render("map_base.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

4.2 Map_guangdong

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

c = (
    Map()
    .add("商家A", [list(z) for z in zip(Faker.guangdong_city, Faker.values())], "广东")
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Map-广东地图"), visualmap_opts=opts.VisualMapOpts()
    )
    .render("map_guangdong.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

4.3 Map_visualmap_piecewise

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

c = (
    Map()
    .add("商家A", [list(z) for z in zip(Faker.provinces, Faker.values())], "china")
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Map-VisualMap(分段型)"),
        visualmap_opts=opts.VisualMapOpts(max_=200, is_piecewise=True),
    )
    .render("map_visualmap_piecewise.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

4.4 Map_world

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

c = (
    Map()
    .add("商家A", [list(z) for z in zip(Faker.country, Faker.values())], "world")
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Map-世界地图"),
        visualmap_opts=opts.VisualMapOpts(max_=200),
    )
    .render("map_world.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

4.5 Population_density_of_hongkong_v2

import ssl

import pyecharts.options as opts
from pyecharts.charts import Map
from pyecharts.datasets import register_url

"""
Gallery 使用 pyecharts 1.1.0 和 echarts-china-cities-js
参考地址: https://echarts.apache.org/examples/editor.html?c=map-HK
"""
ssl._create_default_https_context = ssl._create_unverified_context
# 与 pyecharts 注册,当画香港地图的时候,用 echarts-china-cities-js
register_url("https://echarts-maps.github.io/echarts-china-cities-js")

WIKI_LINK = (
    "http://zh.wikipedia.org/wiki/"
    "%E9%A6%99%E6%B8%AF%E8%A1%8C%E6%94%BF%E5%8D%80%E5%8A%83#cite_note-12"
)
MAP_DATA = [
    ["中西区", 20057.34],
    ["湾仔", 15477.48],
    ["东区", 31686.1],
    ["南区", 6992.6],
    ["油尖旺", 44045.49],
    ["深水埗", 40689.64],
    ["九龙城", 37659.78],
    ["黄大仙", 45180.97],
    ["观塘", 55204.26],
    ["葵青", 21900.9],
    ["荃湾", 4918.26],
    ["屯门", 5881.84],
    ["元朗", 4178.01],
    ["北区", 2227.92],
    ["大埔", 2180.98],
    ["沙田", 9172.94],
    ["西贡", 3368],
    ["离岛", 806.98],
]


NAME_MAP_DATA = {
    # "key": "value"
    # "name on the * map": "name in the MAP DATA",
    "中西区": "中西区",
    "东区": "东区",
    "离岛区": "离岛",
    "九龙城区": "九龙城",
    "葵青区": "葵青",
    "观塘区": "观塘",
    "北区": "北区",
    "西贡区": "西贡",
    "沙田区": "沙田",
    "深水埗区": "深水埗",
    "南区": "南区",
    "大埔区": "大埔",
    "荃湾区": "荃湾",
    "屯门区": "屯门",
    "湾仔区": "湾仔",
    "黄大仙区": "黄大仙",
    "油尖旺区": "油尖旺",
    "元朗区": "元朗",
}

(
    Map(init_opts=opts.InitOpts(width="1400px", height="800px"))
    .add(
        series_name="香港18区人口密度",
        maptype="香港",
        data_pair=MAP_DATA,
        name_map=NAME_MAP_DATA,
        is_map_symbol_show=False,
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="香港18区人口密度 (2011)",
            subtitle="人口密度数据来自Wikipedia",
            subtitle_link=WIKI_LINK,
        ),
        tooltip_opts=opts.TooltipOpts(
            trigger="item", formatter="{b}<br/>{c} (p / km2)"
        ),
        visualmap_opts=opts.VisualMapOpts(
            min_=800,
            max_=50000,
            range_text=["High", "Low"],
            is_calculable=True,
            range_color=["lightskyblue", "yellow", "orangered"],
        ),
    )
    .render("population_density_of_HongKong_v2.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

4.6 Population_density_of_hongkong


import asyncio
from aiohttp import TCPConnector, ClientSession

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

"""
Gallery 使用 pyecharts 1.1.0
参考地址: https://echarts.apache.org/examples/editor.html?c=map-HK
"""

WIKI_LINK = (
    "http://zh.wikipedia.org/wiki/"
    "%E9%A6%99%E6%B8%AF%E8%A1%8C%E6%94%BF%E5%8D%80%E5%8A%83#cite_note-12"
)

async def get_json_data(url: str) -> dict:
    async with ClientSession(connector=TCPConnector(ssl=False)) as session:
        async with session.get(url=url) as response:
            return await response.json()

# 下载香港地图
# data = asyncio.run(
#     get_json_data(url="https://echarts.apache.org/examples/data/asset/geo/HK.json")
# )

loop = asyncio.get_event_loop()
data = loop.run_until_complete(get_json_data(url="https://echarts.apache.org/examples/data/asset/geo/HK.json"))

MAP_DATA = [
    ["中西区", 20057.34],
    ["湾仔", 15477.48],
    ["东区", 31686.1],
    ["南区", 6992.6],
    ["油尖旺", 44045.49],
    ["深水埗", 40689.64],
    ["九龙城", 37659.78],
    ["黄大仙", 45180.97],
    ["观塘", 55204.26],
    ["葵青", 21900.9],
    ["荃湾", 4918.26],
    ["屯门", 5881.84],
    ["元朗", 4178.01],
    ["北区", 2227.92],
    ["大埔", 2180.98],
    ["沙田", 9172.94],
    ["西贡", 3368],
    ["离岛", 806.98],
]


NAME_MAP_DATA = {
    # "key": "value"
    # "name on the * map": "name in the MAP DATA",
    "Central and Western": "中西区",
    "Eastern": "东区",
    "Islands": "离岛",
    "Kowloon City": "九龙城",
    "Kwai Tsing": "葵青",
    "Kwun Tong": "观塘",
    "North": "北区",
    "Sai Kung": "西贡",
    "Sha Tin": "沙田",
    "Sham Shui Po": "深水埗",
    "Southern": "南区",
    "Tai Po": "大埔",
    "Tsuen Wan": "荃湾",
    "Tuen Mun": "屯门",
    "Wan Chai": "湾仔",
    "Wong Tai Sin": "黄大仙",
    "Yau Tsim Mong": "油尖旺",
    "Yuen Long": "元朗",
}

(
    Map(init_opts=opts.InitOpts(width="1400px", height="800px"))
    .add_js_funcs("echarts.registerMap('HK', {});".format(data))
    .add(
        series_name="香港18区人口密度",
        maptype="HK",
        data_pair=MAP_DATA,
        name_map=NAME_MAP_DATA,
        is_map_symbol_show=False,
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="香港18区人口密度 (2011)",
            subtitle="人口密度数据来自Wikipedia",
            subtitle_link=WIKI_LINK,
        ),
        tooltip_opts=opts.TooltipOpts(
            trigger="item", formatter="{b}<br/>{c} (p / km2)"
        ),
        visualmap_opts=opts.VisualMapOpts(
            min_=800,
            max_=50000,
            range_text=["High", "Low"],
            is_calculable=True,
            range_color=["lightskyblue", "yellow", "orangered"],
        ),
    )
    .render("population_density_of_HongKong.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

4.7 Map_china_citites

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

c = (
    Map()
    .add(
        "商家A",
        [list(z) for z in zip(Faker.guangdong_city, Faker.values())],
        "china-cities",
        label_opts=opts.LabelOpts(is_show=False),
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Map-中国地图(带城市)"),
        visualmap_opts=opts.VisualMapOpts(),
    )
    .render("map_china_cities.html")
)

4.8 Map_without_label

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

c = (
    Map()
    .add("商家A", [list(z) for z in zip(Faker.provinces, Faker.values())], "china")
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(title_opts=opts.TitleOpts(title="Map-不显示Label"))
    .render("map_without_label.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

4.9 Map_visualmap

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

c = (
    Map()
    .add("商家A", [list(z) for z in zip(Faker.provinces, Faker.values())], "china")
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Map-VisualMap(连续型)"),
        visualmap_opts=opts.VisualMapOpts(max_=200),
    )
    .render("map_visualmap.html")
)

【Web开发】Python实现Web图表功能(pyecharts入门学习)

4.10 Map3d_china_base

from pyecharts import options as opts
from pyecharts.charts import Map3D
from pyecharts.globals import ChartType

c = (
    Map3D()
    .add_schema(
        itemstyle_opts=opts.ItemStyleOpts(
            color="rgb(5,101,123)",
            opacity=1,
            border_width=0.8,
            border_color="rgb(62,215,213)",
        ),
        map3d_label=opts.Map3DLabelOpts(
            is_show=True,
            text_style=opts.TextStyleOpts(
                color="#fff", font_size=16, background_color="rgba(0,0,0,0)"
            ),
        ),
        emphasis_label_opts=opts.LabelOpts(is_show=True),
        light_opts=opts.Map3DLightOpts(
            main_color="#fff",
            main_intensity=1.2,
            is_main_shadow=False,
            main_alpha=55,
            main_beta=10,
            ambient_intensity=0.3,
        ),
    )
    .add(series_name="", data_pair="", maptype=ChartType.MAP3D)
    .set_global_opts(
        title_opts=opts.TitleOpts(title="全国行政区划地图-Base"),
        visualmap_opts=opts.VisualMapOpts(is_show=False),
        tooltip_opts=opts.TooltipOpts(is_show=True),
    )
    .render("map3d_china_base.html")
)

4.11 Map_globe_base

import pyecharts.options as opts
from pyecharts.charts import MapGlobe
from pyecharts.faker import POPULATION

data = [x for _, x in POPULATION[1:]]
low, high = min(data), max(data)

c = (
    MapGlobe()
    .add_schema()
    .add(
        maptype="world",
        series_name="World Population",
        data_pair=POPULATION[1:],
        is_map_symbol_show=False,
        label_opts=opts.LabelOpts(is_show=False),
    )
    .set_global_opts(
        visualmap_opts=opts.VisualMapOpts(
            min_=low,
            max_=high,
            range_text=["max", "min"],
            is_calculable=True,
            range_color=["lightskyblue", "yellow", "orangered"],
        )
    )
    .render("map_globe_base.html")
)

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭ 如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O??? 如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡) 感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

<font color=purple face=华文行楷 size="5">"侬今葬花人笑痴,他年葬侬知是谁?"