【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~

前言

pyecharts 是一个用于生成 Echarts 图表的Python库。Echarts是百度开源的一个数据可视化 JS 库,可以生成一些非常酷炫的图表。

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第1张图片
Pyecharts在1.x版本之后迎来重大更新,与老版本(0.5X)已是两个完全不同的版本,所以很多小伙伴在使用Pyecharts出现了类似'pyecharts' has no attribute 'xxx'的报错,那是因为你安装了1.x的版本却使用了0.5x的调用方法。

  • 当然如果你更习惯使用0.5X版本的可以通过如下语句来进行安装:
    pip install pyecharts==0.5.11
  • 安装1.x版本(仅支持Python 3.6+):
    pip install pyecharts

本文将会介绍Pyecharts1.x版本的使用方法,本文所有语句均基于v1.6.2,通过以下语句查询使用pyecharts版本:

import pyecharts

print(pyecharts.__version__)

基本使用

链式调用

pyecharts在v1.x之后支持链式调用,具体语句如下:

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

# 示例数据
cate = ['Apple', 'Huawei', 'Xiaomi', 'Oppo', 'Vivo', 'Meizu']
data1 = [123, 153, 89, 107, 98, 23]
data2 = [56, 77, 93, 68, 45, 67]

# 1.x版本支持链式调用
bar = (Bar()
       .add_xaxis(cate)
       .add_yaxis('电商渠道', data1)
       .add_yaxis('门店', data2)
       .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
      )
# 在jupyter notebook总渲染
bar.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第2张图片

单独调用

不习惯链式调用的开发者依旧可以单独调用方法。

# 单独调用
bar = Bar()
bar.add_xaxis(cate)
bar.add_yaxis('电商渠道', data1)
bar.add_yaxis('门店', data2)
bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
bar.render_notebook()

全局配置

可以通过全局配置(.set_global_opts():)控制以下区域
【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第3张图片
【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第4张图片
使用示例如下:

"""
全局配置项使用示例:
1. 标题 & 副标题
2. 关闭图例
3. 显示工具箱
"""
bar = (Bar()
       .add_xaxis(cate)
       .add_yaxis('电商渠道', data1)
       .add_yaxis('门店', data2)
       .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"),
                        toolbox_opts=opts.ToolboxOpts(),
                        legend_opts=opts.LegendOpts(is_show=False))
      )

bar.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第5张图片

系列配置

可以通过系列配置(.set_series_opts())控制图表中的文本,线样式,标记等,使用示例如下:

"""
系列配置项使用示例:
1. 不显示数值
2. 标记每个系列的最大值
"""
bar = (Bar()
       .add_xaxis(cate)
       .add_yaxis('电商渠道', data1)
       .add_yaxis('门店', data2)
       .set_series_opts(label_opts=opts.LabelOpts(is_show=False),
                        markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max", name="最大值"),]))
       .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
      )

bar.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第6张图片

基本图表

饼图

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

# 示例数据
cate = ['Apple', 'Huawei', 'Xiaomi', 'Oppo', 'Vivo', 'Meizu']
data = [153, 124, 107, 99, 89, 46]

pie = (Pie()
       .add('', [list(z) for z in zip(cate, data)],
            radius=["30%", "75%"],
            rosetype="radius")
       .set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本示例", subtitle="我是副标题"))
       .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
      )

pie.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第7张图片

折线图

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

# 示例数据
cate = ['Apple', 'Huawei', 'Xiaomi', 'Oppo', 'Vivo', 'Meizu']
data1 = [123, 153, 89, 107, 98, 23]
data2 = [56, 77, 93, 68, 45, 67]

"""
折线图示例:
1. is_smooth 折线 OR 平滑
2. markline_opts 标记线 OR 标记点
"""
line = (Line()
       .add_xaxis(cate)
       .add_yaxis('电商渠道', data1, 
                  markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]))
       .add_yaxis('门店', data2, 
                  is_smooth=True, 
                  markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(name="自定义标记点", 
                                                                             coord=[cate[2], data2[2]], value=data2[2])]))
       .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例", subtitle="我是副标题"))
      )

line.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第8张图片

漏斗图

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

# 示例数据
cate = ['访问', '注册', '加入购物车', '提交订单', '付款成功']
data = [30398, 15230, 10045, 8109, 5698]

"""
漏斗图示例:
1. sort_控制排序,默认降序;
2. 标签显示位置
"""
funnel = (Funnel()
          .add("用户数", [list(z) for z in zip(cate, data)], 
               sort_='ascending',
               label_opts=opts.LabelOpts(position="inside"))
          .set_global_opts(title_opts=opts.TitleOpts(title="Funnel-基本示例", subtitle="我是副标题"))
         )

funnel.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第9张图片

热力图

from pyecharts.charts import HeatMap
from pyecharts import options as opts
from pyecharts.faker import Faker
import random

# 示例数据
data = [[i, j, random.randint(0, 50)] for i in range(24) for j in range(7)]

heat = (HeatMap()
        .add_xaxis(Faker.clock)
        .add_yaxis("访客数", 
                   Faker.week, 
                   data,
                   label_opts=opts.LabelOpts(is_show=True, position="inside"))
        .set_global_opts(
            title_opts=opts.TitleOpts(title="HeatMap-基本示例", subtitle="我是副标题"),
            visualmap_opts=opts.VisualMapOpts(),
            legend_opts=opts.LegendOpts(is_show=False))
       )

heat.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第10张图片

日历图

from pyecharts.charts import Calendar
from pyecharts import options as opts
import random
import datetime

# 示例数据
begin = datetime.date(2019, 1, 1)
end = datetime.date(2019, 12, 31)
data = [[str(begin + datetime.timedelta(days=i)), random.randint(1000, 25000)]
        for i in range((end - begin).days + 1)]

"""
日历图示例:
"""
calendar = (
        Calendar()
        .add("微信步数", data, calendar_opts=opts.CalendarOpts(range_="2019"))
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Calendar-基本示例", subtitle="我是副标题"),
            legend_opts=opts.LegendOpts(is_show=False),
            visualmap_opts=opts.VisualMapOpts(
                max_=25000,
                min_=1000,
                orient="horizontal",
                is_piecewise=True,
                pos_top="230px",
                pos_left="100px",
            )
        )
    )

calendar.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第11张图片

地理系图表

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

province = ['广东', '湖北', '湖南', '四川', '重庆', '黑龙江', '浙江', '山西', '河北', '安徽', '河南', '山东', '西藏']
data = [(i, random.randint(50, 150)) for i in province]

_map = (
        Map()
        .add("销售额", data, "china")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Map-基本示例"),
            legend_opts=opts.LegendOpts(is_show=False),
            visualmap_opts=opts.VisualMapOpts(max_=200, is_piecewise=True),
        )
    )

_map.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第12张图片

地理热点图

from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.globals import ChartType
import random

province = ['武汉', '十堰', '鄂州', '宜昌', '荆州', '孝感', '黄石', '咸宁', '仙桃']
data = [(i, random.randint(50, 150)) for i in province]

geo = (Geo()
        .add_schema(maptype="湖北")
        .add("门店数", data,
            type_=ChartType.HEATMAP)
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            visualmap_opts=opts.VisualMapOpts(),
            legend_opts=opts.LegendOpts(is_show=False),
            title_opts=opts.TitleOpts(title="Geo-湖北热力地图"))
      )

geo.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第13张图片

3D散点图

from pyecharts import options as opts
from pyecharts.charts import Scatter3D
from pyecharts.faker import Faker
import random


data = [[random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)]
        for _ in range(1000)]

scatter3D = (Scatter3D()
             .add("", data)
             .set_global_opts(
                 title_opts=opts.TitleOpts("Scatter3D-基本示例"),
                 visualmap_opts=opts.VisualMapOpts(range_color=Faker.visual_color))
            )

scatter3D.render_notebook()

其他特性

xy轴翻转

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

# 示例数据
cate = ['Apple', 'Huawei', 'Xiaomi', 'Oppo', 'Vivo', 'Meizu']
data1 = [123, 153, 89, 107, 98, 23]
data2 = [56, 77, 93, 68, 45, 67]

bar = (Bar()
       .add_xaxis(cate)
       .add_yaxis('电商渠道', data1)
       .add_yaxis('门店', data2)
       .set_global_opts(title_opts=opts.TitleOpts(title="XY轴翻转-基本示例", subtitle="我是副标题"))
       .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
       .reversal_axis()
      )

bar.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第14张图片

组合图表

from pyecharts import options as opts
from pyecharts.charts import Map, Bar, Grid
from pyecharts.globals import ChartType, ThemeType
import random

province = ['武汉', '十堰', '鄂州', '宜昌', '荆州', '孝感', '黄石', '咸宁', '仙桃']
data = [324, 125, 145, 216, 241, 244, 156, 278, 169]

bar = (Bar()
       .add_xaxis(province)
       .add_yaxis('营业额', data)
       .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
       .set_global_opts(
            title_opts=opts.TitleOpts(title="Grid-Bar")
        )
      )

line = (Line()
       .add_xaxis(province)
       .add_yaxis('营业额', data, 
                  markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]))
       .set_global_opts(title_opts=opts.TitleOpts(title="Grid-Line", pos_top="48%"))
      )

grid = (
        Grid()
        .add(bar, grid_opts=opts.GridOpts(pos_bottom="60%"))
        .add(line, grid_opts=opts.GridOpts(pos_top="60%"))
    )

grid.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第15张图片

主题设置

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

# 示例数据
cate = ['Apple', 'Huawei', 'Xiaomi', 'Oppo', 'Vivo', 'Meizu']
data1 = [123, 153, 89, 107, 98, 23]
data2 = [56, 77, 93, 68, 45, 67]

"""
主题设置:
默认white
"""
bar = (Bar(init_opts=opts.InitOpts(theme=ThemeType.ROMANTIC))
       .add_xaxis(cate)
       .add_yaxis('电商渠道', data1)
       .add_yaxis('门店', data2)
       .set_series_opts(label_opts=opts.LabelOpts(is_show=False),
                        markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max", name="最大值"),]))
       .set_global_opts(title_opts=opts.TitleOpts(title="Theme-ROMANTIC"))
      )

bar.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第16张图片

时间轴

from pyecharts import options as opts
from pyecharts.charts import Bar, Timeline
from pyecharts.globals import ThemeType
import random

# 示例数据
cate = ['Apple', 'Huawei', 'Xiaomi', 'Oppo', 'Vivo', 'Meizu']

tl = Timeline()
for i in range(2015, 2020):
    bar = (
        Bar()
        .add_xaxis(cate)
        .add_yaxis("线上", [random.randint(50, 150) for _ in cate])
        .add_yaxis("门店", [random.randint(100, 200) for _ in cate])
        .set_global_opts(title_opts=opts.TitleOpts("手机品牌{}年营业额".format(i)))
    )
    tl.add(bar, "{}年".format(i))
    
tl.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第17张图片

航线图

from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.globals import ChartType, SymbolType, ThemeType
import requests

r = requests.get('https://echarts.baidu.com/examples/data-gl/asset/data/flights.json')
data = r.json()

city = ['Beijing']
airports_code = []

geo = Geo(init_opts=opts.InitOpts(theme=ThemeType.DARK))
for i, airport in enumerate(data['airports']):
    if airport[1] in city:
        geo.add_coordinate(i, airport[3], airport[4])
        airports_code.append(i)

route = [(x, y) for _, x, y in data['routes'] if x in airports_code]


geo.add_schema(maptype="world",
                itemstyle_opts=opts.ItemStyleOpts())
geo.add("geo", route, 
        is_large = True,
        symbol_size=0,
        type_='lines',
        is_polyline=True,
        effect_opts=opts.EffectOpts(symbol='pin', symbol_size=1, trail_length=1, color="rgba(255,69,0,0.9)"),
        linestyle_opts=opts.LineStyleOpts(curve=0.2, width=0.2, color='rgb(245,245,245)',opacity=0.05)
       )
geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
geo.set_global_opts(title_opts=opts.TitleOpts(title="北京发出所有航线"),
                   legend_opts=opts.LegendOpts(is_show=False))


geo.render_notebook()

【Python可视化】超详细Pyecharts 1.x教程,让你的图表动起来~_第18张图片


整理不易,欢迎点赞收藏✨✨✨

你可能感兴趣的:(数据可视化)