桑基图(Sankey diagram),即桑基能量分流图或桑基能量平衡图,是一种特定类型的流程图,主要由边、流量和节点组成,其中边代表流动的数据,流量代表流动数据的具体数值,节点代表不同的分类,图中延伸的边的宽度对应流量的大小
最初因1898年Matthew Henry Phineas Riall Sankey绘制的“蒸汽机的能源效率图”而闻名,故以其名字命名为“桑基图”
本篇使用的数据集是对受访者关于“选择工作的最主要原因”的调查结果,受访者按学历分成“研究生及以上”、“大学本科”、“大学专科”、“高中/中专”、“初中及以下”,“选择工作的最主要原因”分别为“发展前景”、“工资待遇”、“工作地点”、“工作自由度”、“家庭原因”、“入职门槛低”、“兴趣爱好”、“其他”,按父类—子类—数据的格式整理成Excel文件
import numpy as np
import pandas as pd
from pyecharts.charts import Sankey #首次使用需先安装
from pyecharts import options as opts
data = pd.read_excel('C:/Users/dell-pc/Desktop/data.xlsx')
data.head(13) #显示前13行数据
data['父类'].tolist()
data['子类'].tolist()
nodes = list(set(data['父类'].tolist() + data['子类'].tolist()))
nodes
nodes_list = []
for i in nodes:
dic = {}
dic["name"] = i
nodes_list.append(dic)
nodes_list
links_list = []
for i in range(len(data)):
dic = {}
dic['source'] = data.iloc[i,0] #定义字典的"source"为数据集的第一列"父类"
dic['target'] = data.iloc[i,1] #定义字典的"target"为数据集的第二列"子类"
dic['value'] = int(data.iloc[i,2]) #定义字典"value"为数据集第三列"数据"(使用int函数强制转换)
links_list.append(dic)
links_list
pic = (
Sankey()
.add(
"受访者人数", #设置图例名称
nodes_list, #传入节点数据
links_list, #传入边和流量数据
linestyle_opt = opts.LineStyleOpts(opacity = 0.5, curve = 0.5, color = "source"), #设置透明度、弯曲度、颜色,color可以是"source"或"target"
label_opts = opts.LabelOpts(position = "right"), #设置标签位置,position可以是"top"、"left"、"right"、"bottom"等
node_width = 20, #设置节点矩形的宽度
node_gap = 10, #设置节点矩形的距离
)
.set_global_opts(title_opts=opts.TitleOpts(title="选择工作的最主要原因")) #设置图表标题
)
pic.render_notebook()
P.S. 节点布局的顺序和位置可手动调节
pic = (
Sankey()
.add(
"受访者人数", #设置图例名称
nodes_list, #传入节点数据
links_list, #传入边和流量数据
linestyle_opt = opts.LineStyleOpts(opacity = 0.5, curve = 0.5, color = "source"), #设置透明度、弯曲度、颜色,color可以是"source"或"target"
label_opts = opts.LabelOpts(position = "bottom"), #设置标签位置,position可以是"top"、"left"、"right"、"bottom"等
node_width = 20, #设置节点矩形的宽度
node_gap = 20, #设置节点矩形的距离
orient="vertical", #设置节点布局的方向,可以是"horizontal"或"vertical"
)
.set_global_opts(title_opts=opts.TitleOpts(title="选择工作的最主要原因")) #设置图表标题
)
pic.render_notebook()