Apple.Turicreate模块中本来是有可视化.show()模块,但是4.0版本之后移除了。 感谢apple工程师耐心+
详细推荐了networkX。于是乎摸索了一下,如何用networkx与Apple.Turicreate互动。

来一个例子开场:

import networkx as nx
%matplotlib inline
from turicreate import SGraph, Vertex, Edge ,SFramedef Networkx2Turi(g,direct = 'directed',weight = False):# 是否有向    if direct == 'directed':draw_g = nx.DiGraph()  elif direct == 'undirected':draw_g = nx.Graph()  elif direct == 'multi.directed':draw_g = nx.MultiDiGraph()elif direct == 'multi.undirected':draw_g = nx.MultiGraph() # 加载数据if weight:edge_list = [tuple(g_list.values()) for g_list in g.edges[['__src_id','__dst_id','weight']]]draw_g.add_weighted_edges_from(edge_list)else:edge_list = [tuple(g_list.values()) for g_list in g.edges[['__src_id','__dst_id']]]draw_g.add_edges_from(edge_list)return draw_g# load data
url = 'https://static.turi.com/datasets/bond/bond_vertices.csv'
vertex_data = SFrame.read_csv(url)
url = 'https://static.turi.com/datasets/bond/bond_edges.csv'
edge_data = SFrame.read_csv(url)
csg = SGraph(vertices=SFrame(vertex_data), edges=edge_data, vid_field='name',src_field='src', dst_field='dst')
csg.edges['weight'] = range(len(csg.edges))# draw directed graph
draw_g = Networkx2Turi(csg,direct = 'directed',weight = True)
nx.draw(draw_g, node_color='y', with_labels=True, node_size=500)  


.


一、函数Networkx2Turi()

自己简单写了一个划算适用的小函数:

Networkx2Turi(g,direct = 'directed',weight = False)
  • 其中g就是apple.turicreate的一个graph内容;
  • direct是选择画图的模式,有向(directed)与无向(undirected),还有一个multi模式下的有向与无向(具体可见地址)
  • weight
    代表是否需要加权,如果选择加权模式,需要在SGraph().edges中加入权重列。也就是这句:csg.edges['weight']
    = range(len(csg.edges))

.


二、函数nx.draw()

这个函数是networkx中的,主函数:

nx.draw(draw_g, pos,node_color='y', with_labels=True, node_size=500)  
  • draw_g,代表networkx中的graph格式,并不能直接用turicreate的graph。Networkx2Turi()就是这么生成的。
  • pos代表每个点的位置,一般来说很难定义这个坐标。
  • node_color每个点的颜色,此时的y代表黄色;
  • with_labels每个顶点是否带文字内容;
  • node_size每个点的大小。

.


三、更好地绘图

我们想根据每个点的重要性来判定顶点的大小与颜色,来看一下apple.turicreate中如何获得顶点的度:

# 如何要绘制不同点的颜色
# node_color=range(len(csg.vertices))
def increment_degree(src, edge, dst):src['degree'] += 1dst['degree'] += 1return (src, edge, dst)
csg.vertices['degree'] = 0csg = csg.triple_apply(increment_degree, mutated_fields=['degree'])
csg.vertices

来看看根据每个顶点的degree来调整颜色以及大小。

  • 调整颜色的案例:
node_color=[float(v) for v in csg.vertices['degree']]
nx.draw(draw_g, node_color=node_color, with_labels=True, node_size=500)

  • 调整顶点大小的案例:
# 调整每个的大小
node_size= [i * 150 for i in range(len(csg.vertices)) ]
nx.draw(draw_g, node_color=node_color, with_labels=True, node_size=node_size) 


顶点是否带标签信息(with_labels=False):

.


四、Networkx中几款图

这两款特别好看,笔者摘录。可看官网:
https://networkx.github.io/documentation/networkx-1.10/examples/drawing/index.html

4.1 Knuth Miles

import networkx as nxdef miles_graph():""" Return the cites example graph in miles_dat.txtfrom the Stanford GraphBase."""# open file miles_dat.txt.gz (or miles_dat.txt)import gzipfh = gzip.open('knuth_miles.txt.gz','r')G=nx.Graph()G.position={}G.population={}cities=[]for line in fh.readlines():line = line.decode()if line.startswith("*"): # skip commentscontinuenumfind=re.compile("^\d+")if numfind.match(line): # this line is distancesdist=line.split()for d in dist:G.add_edge(city,cities[i],weight=int(d))i=i+1else: # this line is a city, position, populationi=1(city,coordpop)=line.split("[")cities.insert(0,city)(coord,pop)=coordpop.split("]")(y,x)=coord.split(",")G.add_node(city)# assign position - flip x axis for matplotlib, shift originG.position[city]=(-int(x)+7500,int(y)-3000)G.population[city]=float(pop)/1000.0return Gif __name__ == '__main__':import networkx as nximport reimport sysG=miles_graph()print("Loaded miles_dat.txt containing 128 cities.")print("digraph has %d nodes with %d edges"\%(nx.number_of_nodes(G),nx.number_of_edges(G)))# make new graph of cites, edge if less then 300 miles between themH=nx.Graph()for v in G:H.add_node(v)for (u,v,d) in G.edges(data=True):if d['weight'] < 300:H.add_edge(u,v)# draw with matplotlib/pylabtry:import matplotlib.pyplot as pltplt.figure(figsize=(8,8))# with nodes colored by degree sized by populationnode_color=[float(H.degree(v)) for v in H]nx.draw(H,G.position,node_size=[G.population[v] for v in H],node_color=node_color,with_labels=False)# scale the axes equallyplt.xlim(-5000,500)plt.ylim(-2000,3500)plt.savefig("knuth_miles.png")except:pass

.

4.2 Random Geometric Graph

import networkx as nx
import matplotlib.pyplot as pltG=nx.random_geometric_graph(200,0.125)
# position is stored as node attribute data for random_geometric_graph
pos=nx.get_node_attributes(G,'pos')# find node near center (0.5,0.5)
dmin=1
ncenter=0
for n in pos:x,y=pos[n]d=(x-0.5)**2+(y-0.5)**2if d<dmin:ncenter=ndmin=d# color by path length from node near center
p=nx.single_source_shortest_path_length(G,ncenter)
# 主函数
plt.figure(figsize=(8,8))
nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4)
nx.draw_networkx_nodes(G,pos,nodelist=p.keys(),node_size=80,node_color=p.values(),cmap=plt.cm.Reds_r)# 去除背景颜色
#plt.xlim(-0.05,1.05)
#plt.ylim(-0.05,1.05)
#plt.axis('off')
#plt.savefig('random_geometric_graph.png')
#plt.show()


公众号“素质云笔记”定期更新博客内容:

关系图︱python 关系网络的可视化NetworkX(与Apple.Turicreate深度契合)相关推荐

  1. python绘制社会关系网络图_文本分析之制作网络关系图——Python

    今天给大家带来我一个脚本,用来分析社会网络关系. 这个图我没有用到gephi或者其他的工具,是我用python纯脚本运行出来的.简单的实现了封装,大家有兴趣可以下载下脚本,运行下. 原理知识 我就简单 ...

  2. 实体-关系图转换为关系模型

    1.逻辑设计概述   概念结构是独立于任何一种数据模型的,在实际应用中,一般所用的数据库环境已经给定(如SQL Server或Oracel或MySql),本文讨论从概念结构向逻辑结构的转换问题.    ...

  3. 离散数学【关系】习题解析 序偶,直积,关系图,关系矩阵,哈斯图

    下面是习题与解析 文章目录 第一题 序偶与类型 第二题 关系图,矩阵与类型 第三题关系图,矩阵与类型 第四题 复合关系 第五题 求t( R) 第六题 求表达式 第七题 求关系图等价类 第八题 写出序偶 ...

  4. python词汇网络分析_文本分析之制作网络关系图——Python

    今天给大年夜家带来我一个脚本,用来分析社会收集关系. 这个图我没有效到gephi或者其他的对象,是我用python纯脚本运行出来的.简单的实现了封装,大年夜家有兴趣可以下载下脚本,运行下. 1.建好小 ...

  5. python networkx模块,python复杂网络处理模块networkx

    最近开始认真的学习发现一个 python 好玩的模块 以下内容为网上的文章整合 networkx在02年5月产生,是用python语言编写的软件包,便于用户对复杂网络进行创建.操作和学习.利用netw ...

  6. python复杂网络点图可视化_Python学习工具:9个用来爬取网络站点的 Python 库

    Python学习工具 :总结了9个用来爬取网络站点的Python 库,有你在用的吗? Scrapy 一个开源和协作框架,用于从网站中提取所需的数据. 以快速,简单,可扩展的方式. cola 一个分布式 ...

  7. python复杂网络点图可视化_数据分析:R与Python怎么选?

    作者介绍 知春里@伟仔 不知名数据科学家. 持续写<数据分析>和<数据产品>的系列文章,欢迎关注. 01 选R还是Python? "球鞋是买阿迪还是买耐克?" ...

  8. python画仿真图-Python数据分析:绘图可视化之matplotlib入门

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理 以下文章来源于码客趣分享,作者码客趣分享 matplotlib的通常引入约定 ...

  9. ER图 实体关系图 弱关系 弱实体 概化 全部概化 外键

    pos文件 提取码:timw 链接: 提取码:timw –来自百度网盘超级会员V4的分享

最新文章

  1. mysql索引空间太大_MySQL优化索引
  2. 课程导入导出中的知识点操作
  3. UVA11997求前k个和,多路归并问题
  4. Markdown基本语法【转】
  5. word中如何对公式插入题注和引用
  6. 爬虫学习二: bs4 xpath re
  7. 问题记录——sqlserver视图重命名的陷阱
  8. windows 远程连接mongo_MongoDB 在windows服务器安装部署与远程访问配置
  9. 数值优化-梯度下降法
  10. Kali Linux镜像安装(1)
  11. 同步带周长计算公式_同步带选型计算方法
  12. 2022年电子邮箱哪个好用?邮箱大全测评来了,请及时查看哦
  13. GStreamer修改解码器默认优先级
  14. linux的if语句并且命令,linux命令:if语句练习
  15. 入侵提权过程中猜解linux路径与windows路径,网站路径暴力
  16. 超文本标记语言是指Java_超文本标记语言(HTML)
  17. uni-app的介绍
  18. 买服务器为何选择华为云?
  19. 伟景行Citymaker高亮图层的内元素CSharp
  20. 色彩大全 Android 颜色值

热门文章

  1. 你真的了解UIButton、UILabel 吗?
  2. web.xml文件中的web-app元素 部署
  3. 图解操作系统系列-概述
  4. poj 2987 Firing (最大权 闭合 图)
  5. TypeScript_学习笔记
  6. bootstrap下的双选时间插件使用方法
  7. [javaSE] 集合工具类(Collections-sort)
  8. Dom对象与jQuery对象的转换
  9. Python学习笔记(六)—几个标准类型内建函数
  10. Python安装时import matplotlib.pyplot as plt报错