Matplotlib和Networkx - 绘制自循环节点

时间:2018-03-17 18:37:26

标签: python matplotlib graph draw networkx

我有这个功能,我想绘制一个自循环。我怎么能这样做?
边缘存在,但我认为这个例子中的一个点是(1,1),我无法添加节点的名称。 我的目标是从邻接矩阵绘制图形。有没有更好的方法来做到这一点?

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch, Circle
import numpy as np

def draw_network(G,pos,ax,sg=None):

    for n in G:
        c=Circle(pos[n],radius=0.05,alpha=0.7)
        ax.add_patch(c)
        G.node[n]['patch']=c
        x,y=pos[n]
    seen={}
    for (u,v,d) in G.edges(data=True):
        n1=G.node[u]['patch']
        n2=G.node[v]['patch']
        rad=0.1
        if (u,v) in seen:
            rad=seen.get((u,v))
            rad=(rad+np.sign(rad)*0.1)*-1
        alpha=0.5
        color='k'

        e = FancyArrowPatch(n1.center,n2.center,patchA=n1,patchB=n2,
                            arrowstyle='-|>',
                            connectionstyle='arc3,rad=%s'%rad,
                            mutation_scale=10.0,
                            lw=2,
                            alpha=alpha,
                            color=color)
        seen[(u,v)]=rad
        ax.add_patch(e)
    return e


G=nx.MultiDiGraph([(1,2),(1,1),(1,2),(2,3),(3,4),(2,4),
                (1,2),(1,2),(1,2),(2,3),(3,4),(2,4)]
                )

pos=nx.spring_layout(G)
ax=plt.gca()
draw_network(G,pos,ax)
ax.autoscale()
plt.axis('equal')
plt.axis('off')

plt.show()

1 个答案:

答案 0 :(得分:4)

似乎你的方法相当先进,使用matplotlib,但我仍然建议使用专门的图形绘图库(as does the networkx documentation(。随着图形越来越大,出现更多问题 - 但问题已经存在已在这些图书馆中解决。

A" go-to"选项为graphviz,可以很好地处理绘制多图。您可以从networkx图形中编写点文件,然后使用其中一个图形绘制工具(例如dot,neato等)。

以下是一个以graph attributesmultigraph edge attributes为基础的示例:

import networkx as nx
from networkx.drawing.nx_agraph import to_agraph 

# define the graph as per your question
G=nx.MultiDiGraph([(1,2),(1,1),(1,2),(2,3),(3,4),(2,4), 
    (1,2),(1,2),(1,2),(2,3),(3,4),(2,4)])

# add graphviz layout options (see https://stackoverflow.com/a/39662097)
G.graph['edge'] = {'arrowsize': '0.6', 'splines': 'curved'}
G.graph['graph'] = {'scale': '3'}

# adding attributes to edges in multigraphs is more complicated but see
# https://stackoverflow.com/a/26694158                    
G[1][1][0]['color']='red'

A = to_agraph(G) 
A.layout('dot')                                                                 
A.draw('multi.png')   

multi-graph with self loops

请注意,您也可以从ipython shell中轻松调用绘图: https://stackoverflow.com/a/14945560