目录

一、官网样例

二、准备工作

        1.样例代码下载

        2.包安装+环境配置

三、经典样例展示

1.样例 Read and write graphs

2.样例 Edge Colormap

3.样例 Circular Tree

4.样例 Random Geometric Graph

5.样例 Atlas

6.样例 画3D图


一、官网样例

用python做关联图谱(也称关联图、关联网络图、关系图等,关注的是关联关系;而用于搭建知识体系时,则被称做知识图谱),有时候我会选择用networkx来实现,因此有了这篇学习笔记。

在学习python某个包的时候,建议去官网跑一遍样例,如果项目比较急,可以先找到所需的目标样例,针对性的深入学习这个案例中的代码写法和语法逻辑等。

networkx2.5的官网案例链接为:Gallery — NetworkX 2.8.5 documentation

中文版的官网链接为:绘图示例 — NetworkX 2.8 文档

链接里不叫 Examples,而叫 Gallery,所以有的同学不一定能马上找到,点开链接后如下图:

二、准备工作

1.样例代码下载

本人已经将官网上几十个样例代码都放在一个jupyter文件“networkx官网学习笔记.ipynb”中,均已跑通,并附带所需文件。跑出的结果图可能会和官网或我的jupyter中的不一样,属于正常情况,因为是随机的。

下载链接为:https://download.csdn/download/weixin_42575233/20330671

2.包安装+环境配置

A、python安装3.8,即安装 Anaconda3-2020.02-Windows-x86_64.exe,大家可以从我给的链接直接下载,链接为:Anaconda3-2020.02-Windows-x86_64.exe.zip-Python文档类资源-CSDN下载

,也可以到官网上找到这个版本下载并安装,最新版本的安装包能跑通大部分代码,但不敢保证全部都OK。

B、安装networkx包,用pip install networkx即可,网上也有很多相关文章,在此不做赘述,若安装还是有问题,请留言咨询我。

C、安装Graphviz,下载链接:graphviz-2.38.msi.zip_graphviz-2.38.msi-Python文档类资源-CSDN下载,安装方法详见“networkx官网学习笔记.ipynb”,其环境变量配置方法如下

        a、找到安装路径,如:C:\Program Files (x86)\Graphviz2.38\bin

        b、右键点击“此电脑”选择“属性”,如下图:

     

          c、搜索“高级系统设置”,选择“环境变量”:

       

         d、将bin文件夹对应的路径添加到 Path环境变量中,即双击下图中的Path,在跳出的窗口点“新建”,输入:“C:\Program Files (x86)\Graphviz2.38\bin”,然后点“确定”,完成安装。 

D、安装pygraphviz

我这边提供python3.8版本的whl文件,下载链接为:pygraphviz-1.6-cp38-cp38-win_amd64.whl-Python文档类资源-CSDN下载

,也可以在网页http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygraphviz 中找到pygraphviz对应版本的.whl文件下载。

打开Anaconda下的prompt,在其中输入“cd 路径” 切换到下载的.whl文件所在路径的文件夹目录,在prompt再输入命令:pip install pygraphviz-1.6-cp38-cp38-win_amd64.whl,开始安装。如果显示successfully,就代表已经安装好啦。

E、画3D图涉及的4个包:PyQt6、mayavi、traits 和 VTK

一定要按照以下方式逐个安装

第一组,PyQt6直接在prompt输入 pip install PyQt6,进行网络安装即可。

第二组,其余3个,则在我给的下载链接:python3.8画3D图必备whl.zip-Python文档类资源-CSDN下载

下载“python3.8画3D图必备whl.zip”,解压后有3个whl,放入你指定的某个文件夹下面,在prompt中定位到该文件夹的路径,然后逐个输入以下代码进行安装(若显示 Successfully installed,但有红字 ERROR,可忽略报错,因为仍能正常运行代码):

pip install mayavi-4.7.2-cp38-cp38-win_amd64.whl

pip install traits-6.1.1-cp38-cp38-win_amd64.whl

pip install VTK-9.0.1-cp38-cp38-win_amd64.whl

三、经典样例展示

1.样例 Read and write graphs

代码如下:

# python3.7环境下运行此段代码,第一次跑会不出图,再次运行即可出图
# Read and write graphs
import matplotlib.pyplot as plt
import networkx as nx

G = nx.grid_2d_graph(5, 5)  # 5x5 grid

# print the adjacency list
for line in nx.generate_adjlist(G):
    print(line)
# write edgelist to grid.edgelist
nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
# read edgelist from grid.edgelist
H = nx.read_edgelist(path="grid.edgelist", delimiter=":")

nx.draw(H)
plt.show()

2.样例 Edge Colormap

 代码如下:

#%% Edge Colormap
import matplotlib.pyplot as plt
import networkx as nx

num = 17
G = nx.star_graph(num)
pos = nx.spring_layout(G)
colors = range(num)
nx.draw(G, pos, node_color='#A0CBE2', edge_color=colors,
        width=4, edge_cmap=plt.cm.Blues, with_labels=True)
plt.show()

3.样例 Circular Tree

代码如下:

# Circular Tree
import matplotlib.pyplot as plt
import networkx as nx

try:
    import pygraphviz
    from networkx.drawing.nx_agraph import graphviz_layout
except ImportError:
    try:
        import pydot
        from networkx.drawing.nx_pydot import graphviz_layout
    except ImportError:
        raise ImportError("This example needs Graphviz and either "
                          "PyGraphviz or pydot")

G = nx.balanced_tree(3, 5)
pos = graphviz_layout(G, prog='twopi', args='')
plt.figure(figsize=(8, 8))
nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False)
plt.axis('equal')
plt.show()

 4.样例 Random Geometric Graph

代码如下:

# Random Geometric Graph
import matplotlib.pyplot as plt
import networkx as nx

G = 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)**2
    if d < dmin:
        ncenter = n
        dmin = d

# color by path length from node near center
p = dict(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=list(p.keys()),
                       node_size=80,
                       node_color=list(p.values()),
                       cmap=plt.cm.Reds_r)

plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.axis('off')
plt.show()

 5.样例 Atlas

代码如下:

#Atlas
import random

try:
    import pygraphviz
    from networkx.drawing.nx_agraph import graphviz_layout
except ImportError:
    try:
        import pydot
        from networkx.drawing.nx_pydot import graphviz_layout
    except ImportError:
        raise ImportError("This example needs Graphviz and either "
                          "PyGraphviz or pydot.")

import matplotlib.pyplot as plt

import networkx as nx
from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic as isomorphic
from networkx.generators.atlas import graph_atlas_g


def atlas6():
    """ Return the atlas of all connected graphs of 6 nodes or less.
        Attempt to check for isomorphisms and remove.
    """

    Atlas = graph_atlas_g()[0:208]  # 208
    # remove isolated nodes, only connected graphs are left
    U = nx.Graph()  # graph for union of all graphs in atlas
    for G in Atlas:
        zerodegree = [n for n in G if G.degree(n) == 0]
        for n in zerodegree:
            G.remove_node(n)
        U = nx.disjoint_union(U, G)

    # iterator of graphs of all connected components
    C = (U.subgraph(c) for c in nx.connected_components(U))

    UU = nx.Graph()
    # do quick isomorphic-like check, not a true isomorphism checker
    nlist = []  # list of nonisomorphic graphs
    for G in C:
        # check against all nonisomorphic graphs so far
        if not iso(G, nlist):
            nlist.append(G)
            UU = nx.disjoint_union(UU, G)  # union the nonisomorphic graphs
    return UU


def iso(G1, glist):
    """Quick and dirty nonisomorphism checker used to check isomorphisms."""
    for G2 in glist:
        if isomorphic(G1, G2):
            return True
    return False


if __name__ == '__main__':
    G = atlas6()

    print("graph has %d nodes with %d edges"
          % (nx.number_of_nodes(G), nx.number_of_edges(G)))
    print(nx.number_connected_components(G), "connected components")

    plt.figure(1, figsize=(8, 8))
    # layout graphs with positions using graphviz neato
    pos = graphviz_layout(G, prog="neato")
    # color nodes the same in each connected subgraph
    C = (G.subgraph(c) for c in nx.connected_components(G))
    for g in C:
        c = [random.random()] * nx.number_of_nodes(g)  # random color...
        nx.draw(g,
                pos,
                node_size=40,
                node_color=c,
                vmin=0.0,
                vmax=1.0,
                with_labels=False
               )
    plt.show()

6.样例 画3D图

代码如下(输出png图片):

# Mayavi: needs mayavi2
# run with ipython -wthread
%matplotlib inline
import networkx as nx
import numpy as np
from mayavi import mlab
mlab.options.offscreen = True

# some graphs to try
# H=nx.krackhardt_kite_graph()
# H=nx.Graph();H.add_edge('a','b');H.add_edge('a','c');H.add_edge('a','d')
# H=nx.grid_2d_graph(4,5)
H = nx.cycle_graph(20)

# reorder nodes from 0,len(G)-1
G = nx.convert_node_labels_to_integers(H)
# 3d spring layout
pos = nx.spring_layout(G, dim=3)
# numpy array of x,y,z positions in sorted node order
xyz = np.array([pos[v] for v in sorted(G)])
# scalar colors
scalars = np.array(list(G.nodes())) + 5

mlab.figure(1, bgcolor=(0, 0, 0))
mlab.clf()

pts = mlab.points3d(xyz[:, 0], xyz[:, 1], xyz[:, 2],
                    scalars,
                    scale_factor=0.1,
                    scale_mode='none',
                    colormap='Blues',
                    resolution=20)

pts.mlab_source.dataset.lines = np.array(list(G.edges()))
tube = mlab.pipeline.tube(pts, tube_radius=0.01)
mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8))

mlab.savefig('mayavi2_spring.png')
mlab.show() # interactive window

完整样例,请大家在我的学习笔记里面,逐个运行看看效果吧!

更多推荐

python关联图谱1 之 networkx官网学习笔记+实例附代码