pyecharts︱交互式pyecharts的相关使用教程

2022-05-09 20:30:19 浏览数 (2)

  • 4.1 柱状图
  • 4.2 折线图
  • 4.3 pandas 绘制相关性热力图

一、简单示例

代码语言:javascript复制
from pyecharts import Bar

attr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
bar = Bar("Bar chart", "precipitation and evaporation one year")
bar.add("precipitation", attr, v1, mark_line=["average"], mark_point=["max", "min"])
bar.add("evaporation", attr, v2, mark_line=["average"], mark_point=["max", "min"])
bar.render()
#bar

其中,bar.render(),是以html形式保存在本地文件中;

bar,是在当前环境下,输出图表。

输出方式还有PDF:

代码语言:javascript复制
bar.render(path="render.png")

同时也可以使用flask/Django进行封装,


二、笔者关注的几个图表

2.1 画出花样的散点图

代码语言:javascript复制
from pyecharts import EffectScatter
es = EffectScatter("动态散点图各种图形示例")
es.add("", [10], [10], symbol_size=20, effect_scale=3.5,
       effect_period=3, symbol="pin")
es.add("", [20], [20], symbol_size=12, effect_scale=4.5,
       effect_period=4,symbol="rect")
es.add("", [30], [30], symbol_size=30, effect_scale=5.5,
       effect_period=5,symbol="roundRect")
es.add("", [40], [40], symbol_size=10, effect_scale=6.5,
       effect_brushtype='fill',symbol="diamond")
es.add("", [50], [50], symbol_size=16, effect_scale=5.5,
       effect_period=3,symbol="arrow")
es.add("", [60], [60], symbol_size=6, effect_scale=2.5,
       effect_period=3,symbol="triangle")
es

2.2 关系图 NetworkX

代码语言:javascript复制
from pyecharts import Graph

nodes = [{"name": "结点1", "symbolSize": 10},
         {"name": "结点2", "symbolSize": 20},
         {"name": "结点3", "symbolSize": 30},
         {"name": "结点4", "symbolSize": 40},
         {"name": "结点5", "symbolSize": 50},
         {"name": "结点6", "symbolSize": 40},
         {"name": "结点7", "symbolSize": 30},
         {"name": "结点8", "symbolSize": 20}]
links = []
for i in nodes:
    for j in nodes:
        links.append({"source": i.get('name'), "target": j.get('name')})
graph = Graph("关系图-力引导布局示例")
graph.add("", nodes, links, is_label_show=True,
          graph_repulsion=8000, graph_layout='circular',
          label_text_color=None)
graph

其中,pyecharts处理不了太复杂的关系图,可以借用: networkx 库(可参考笔者的博文:关系图︱python 关系网络的可视化NetworkX(与Apple.Turicreate深度契合))

代码语言:javascript复制
from __future__ import unicode_literals

import networkx as nx
from networkx.readwrite import json_graph
from pyecharts import Graph

g = nx.Graph()
categories = ['网关', '节点']
g.add_node('FF12C904', name='Gateway 1', symbolSize=40, category=0)
g.add_node('FF12CA02', name='Node 11', category=1)
g.add_node('FF12C326', name='Node 12', category=1)
g.add_node('FF45C023', name='Node 111', category=1)
g.add_node('FF230933', name='Node 1111', category=1)

g.add_edge('FF12C904', 'FF12CA02')
g.add_edge('FF12C904', 'FF12C326')
g.add_edge('FF12CA02', 'FF45C023')
g.add_edge('FF45C023', 'FF230933')

g_data = json_graph.node_link_data(g)
eg = Graph('设备最新拓扑图')
eg.add('Devices', nodes=g_data['nodes'], links=g_data['links'], categories=categories)
# eg.show_config()
eg

2.3 WordCloud(词云图)

代码语言:javascript复制
from pyecharts import options as opts
from pyecharts.charts import Page, WordCloud
from pyecharts.globals import SymbolType


words = [
    ("Sam S Club", 10000),
    ("Macys", 6181),
    ("Amy Schumer", 4386),
    ("Jurassic World", 4055),
    ("Charter Communications", 2467),
    ("Chick Fil A", 2244),
    ("Planet Fitness", 1868),
    ("Pitch Perfect", 1484),
    ("Express", 1112),
    ("Home", 865),
    ("Johnny Depp", 847),
    ("Lena Dunham", 582),
    ("Lewis Hamilton", 555),
    ("KXAN", 550),
    ("Mary Ellen Mark", 462),
    ("Farrah Abraham", 366),
    ("Rita Ora", 360),
    ("Serena Williams", 282),
    ("NCAA baseball tournament", 273),
    ("Point Break", 265),
]


def wordcloud_base() -> WordCloud:
    c = (
        WordCloud()
        .add("", words, word_size_range=[20, 100])
        .set_global_opts(title_opts=opts.TitleOpts(title=""))
    )
    return c

wordcloud_base().render_notebook()

支持中文。

2.4 TreeMap(矩形树图)

矩形树图是一种常见的表达『层级数据』『树状数据』的可视化形式。它主要用面积的方式,便于突出展现出『树』的各层级中重要的节点。

代码语言:javascript复制
from pyecharts import TreeMap

treemap = TreeMap("矩形树图示例", width=1200, height=600)
import os
import json
with open(os.path.join("..", "json", "treemap.json"), "r", encoding="utf-8") as f:
        data = json.load(f)
treemap.add("演示数据", data, is_label_show=True, label_pos='inside')
treemap.render()

三 相关组件

3.1 Grid:并行显示多张图

3.2 Overlap:结合不同类型图表叠加画在同张图上

3.3 Page:同一网页按顺序展示多图

3.4 Timeline:提供时间线轮播多张图


4 相关案例与实践

4.1 柱状图

代码语言:javascript复制
from pyecharts.charts import Bar
from pyecharts import options as opts

index_res = ['favoriteCount', 'likeCount','sharecount', 'commentCount']
index_res_ch = ['收藏数', '喜欢数','分享数', '评论数']

# V1 版本开始支持链式调用
bar = (
    Bar()
    .add_xaxis(list(research_data.index))
    .add_yaxis('收藏数',list(research_data['favoriteCount'])  )
    #.add_yaxis("没有视频",  list(research_data[index_res].ix[0,:])  )
    .set_global_opts(title_opts=opts.TitleOpts(title="收藏/喜欢/分享/评论数"))
)
bar.render_notebook()
  • add_xaxis ,增加x列信息
  • add_yaxis,增加y列信息
  • set_global_opts,设置变量环节
  • render_notebook(),可以直接在jupyter notebook之中进行选择

4.2 折线图

代码语言:javascript复制
import pyecharts.options as opts
from pyecharts.charts import Line


x_data = list(research_data.index)
y_data = list(research_data['favoriteCount']) 

line = (
    Line()
    .set_global_opts(
        tooltip_opts=opts.TooltipOpts(is_show=False),
        xaxis_opts=opts.AxisOpts(type_="category"),
        yaxis_opts=opts.AxisOpts(
            type_="value",
            axistick_opts=opts.AxisTickOpts(is_show=True),
            splitline_opts=opts.SplitLineOpts(is_show=True),
        ),
    )
    .add_xaxis(xaxis_data=x_data)
    .add_yaxis(
        series_name="收藏数",
        y_axis=y_data,
        symbol="emptyCircle",
        is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=False),
    )
    #.render("basic_line_chart.html")
)
line.render_notebook() 

x_data , y_data 都是list

.render(“basic_line_chart.html”),直接存储为html格式

直接打印在jupyter notebook之中

4.3 pandas 绘制相关性热力图

代码语言:javascript复制
corr_data = xiaohongshu_kol[['favoritecount','likecount', 'sharecount']].corr()  # viewcount

values = []
for x in range(corr_data.shape[0]):
    for y in range(corr_data.shape[1]):
        values.append([x,y,corr_data.ix[x,y]])
        
x_colnames = corr_data.index.to_list()
y_colnames = corr_data.columns.to_list()

# 绘图
c = (
    HeatMap()
    .add_xaxis(x_colnames)
    .add_yaxis("corr", y_colnames, values)
    .set_global_opts(
        title_opts=opts.TitleOpts(title="相关矩阵热力图"),
        visualmap_opts=opts.VisualMapOpts(max_=1, is_piecewise=True),
    )
)
c.render_notebook() 

pandas求相关性为一张关联表:

其中,values 是一个【位置x,位置y,相关性】:

代码语言:javascript复制
[[0, 0, 1.0],
 [0, 1, 0.7771863236775227],
 [0, 2, 0.727424900237336],
 [0, 3, 0.09334192707534165],
 [0, 4, 0.004296439662247044],
 [1, 1, 1.0],
 [1, 2, 0.7287852426205351],
 [1, 3, 0.14173048773739305]]

其中,opts.VisualMapOpts(max_=1, is_piecewise=True)代表左下角的比例尺,max_ = 1 代表最大值为1

0 人点赞