关系图

Graph(关系图)

用于展现节点以及节点之间的关系数据。

# 导入pyecharts
import pyecharts
# 检查pyecharts版本
pyecharts.__version__
'0.5.5'
# 导入关系图类
from pyecharts import Graph

模拟微信好友社会关系,并绘图

# 节点
nodes = [{'name': '童秀云', "symbolSize": 12,"category": 0,
          'symbol': 'markPoint','value': 2},
         {'name': '武淑珍', "symbolSize": 12,
          'label': {'normal': {'show': True,'textStyle': {'fontSize': 18},}},
          "category": 0,'value': 2,},
         {'name': '文华', "symbolSize": 25, 'draggable': True,"category": 0,'value': 3},
         {'name': '冉坤', "symbolSize": 25, 'draggable': True,"category": 1,'value': 3},
         {'name': '雕志强', "symbolSize": 12, 'draggable': True,"category": 1,'value': 2},
         {'name': '焦超', "symbolSize": 8, 'draggable': True,"category": 1,'value': 0},
        ]
# 关系
links = [{'source': '童秀云','target': '冉坤','value': '夫妻',
          'lineStyle': {'normal': {'color': 'red', 
                                   'type': 'dotted',  # 点线
                                  }}},
         {'source': '文华','target': '武淑珍', 'value': '朋友',
          'lineStyle': { 'normal': {'opacity': 0.9,  # 透明度
                                    'width': 1,
                                    'curveness': 0.1  # 弯曲程度
                                   }}},
         {'source': '童秀云','target': '文华','value': '同事'},
         {'source': '雕志强','target': '文华','value': '夫妻'},
         {'source': '武淑珍','target': '冉坤','value': '朋友'},
         {'source': '雕志强','target': '冉坤','value': '同事'}
        ]
# 绘图
graph = Graph("微信好友社会关系图", width=500, height=250)
graph.add("姓名", nodes, links, [0,1],
          is_label_show=True,
          label_pos="right",
          graph_repulsion=500,  # 节点之间的斥力因子。默认为 50
#           graph_layout='circular',  # 采用环形布局
          graph_layout='force',  # 采用力引导布局
          label_text_color=None,
         is_rotatelabel=True,  # 是否旋转标签,默认为 False
#           is_roam=False,  #  是否开启鼠标缩放和平移漫游。默认为 True
          is_legend_show=True,
         )
# 保存
# graph.render()
# graph.render(path='微信好友社会关系图.html')
# 展示
graph

吸毒人员社会关系图(模拟数据)

模拟数据

# !pip install faker
Collecting faker
  Downloading https://files.pythonhosted.org/packages/8d/76/d9e1dde824f059c4c7c62229ac4818d774d451822d84939ffc3376930f0b/Faker-0.9.0-py2.py3-none-any.whl (747kB)
Requirement already satisfied: python-dateutil>=2.4 in c:\users\administrator.desktop-j1etdl9\anaconda3\lib\site-packages (from faker) (2.7.3)
Collecting text-unidecode==1.2 (from faker)
  Downloading https://files.pythonhosted.org/packages/79/42/d717cc2b4520fb09e45b344b1b0b4e81aa672001dd128c180fabc655c341/text_unidecode-1.2-py2.py3-none-any.whl (77kB)
Requirement already satisfied: six>=1.10 in c:\users\administrator.desktop-j1etdl9\anaconda3\lib\site-packages (from faker) (1.11.0)
Installing collected packages: text-unidecode, faker
Successfully installed faker-0.9.0 text-unidecode-1.2
import random
random.seed(1026)

# faker 包可以用来生成模拟数据
from faker import Faker
fake = Faker()
fake = Faker('zh_CN')  # 中文简体
# fake = Faker('en')   # 英文
# 生成节点初始数据
num = 80  # 设置姓名数, 可能有重名,所以不一定等于节点数
nodes = []
for _ in range(0, num):
    nodes.append(({'name': fake.name(),
                   'category': random.choice([1, 0]),  # random category
                   'draggable': True}))
# 唯一姓名数
names = set()
for node in nodes:
    names.add(node.get('name'))
names = list(names)
print('共随机生成{}个人,前5个是:\n{}'.format(len(names), names[:5]))
共随机生成80个人,前5个是:
['松建华', '段文', '饶峰', '柳秀梅', '容建']
# 生成节点关系数据
links = []
for _ in range(0, num*2):
    names_tmp = names.copy()
    name = random.choice(names_tmp)
    names_tmp.remove(name)
    target = random.choice(names_tmp)
    j = 1
    for link in links:
        for k, v in link.items():
            if (k==name and v==target) or (v==name and k==target):
                j = 0
    if j:  # 删除重复关系对
        links.append(({'source': name,
                       'target': target,
                       'value': random.choice(["夫妻", "同事", "朋友", "亲戚", "同学"])}))
print('共随机生成{}对关系,前5对是:\n{}'.format(len(links), links[:5]))
共随机生成160对关系,前5对是:
[{'source': '汲兵', 'target': '管强', 'value': '同事'}, {'source': '糜玉华', 'target': '相玉英', 'value': '亲戚'}, {'source': '昌丽丽', 'target': '唐雪梅', 'value': '夫妻'}, {'source': '夔杰', 'target': '饶峰', 'value': '朋友'}, {'source': '冯桂英', 'target': '容建', 'value': '亲戚'}]
# 计算关系
connections = {}
# source to target
names2 = set()
for link in links:
    names2.add(link.get('source'))
for name in names2:
    c = 0
    for _ in links:
        if _.get('source') == name:
            c += 1
    connections[name] = c
# connections
# target to source
names3 = set()
for link in links:
    names3.add(link.get('target'))
for name in names3:
    c = 0
    for _ in links:
        if _.get('target') == name:
            c += 1
    if connections.get(name):
        connections[name] += c
    else:
        connections[name] = c
# print(connections)
# 添加关系数和节点大小参数到节点中
for node in nodes:
    for name, value in connections.items():
        if node.get('name') == name:
            node['value'] = value
            node['symbolSize'] = value * 4 + 5
from pyecharts import Graph

graph = Graph("吸毒人员社会关系图", "模拟数据", width=1100, height=700)
graph.add("姓名:",  # 提示框名称
          nodes,  # 节点数据
          links,  # 结点间的关系数据
          categories=[0, 1],  # 结点分类的类目,结点可以指定分类,也可以不指定
          is_label_show=True,  # 是否显示节点标签
          label_pos="top",  # 节点标签位置
          graph_repulsion=180,  # 节点之间的斥力因子。默认为 50
#           graph_layout='circular',  # 采用环形布局
          graph_layout='force',  # 采用力引导布局
          label_text_color=None,
          is_rotatelabel=True,  # 是否旋转标签,默认为 False
#           is_roam=False,  #  是否开启鼠标缩放和平移漫游。默认为 True
         )
graph.render(path='吸毒人员社会关系图(模拟数据).html')
graph

你可能感兴趣的:(数据科学入门到精通,数据科学)