Drawing a custom diagram in python

2019-06-04 22:03发布

问题:

I wanna draw something like this :

The closest thing to this I could find was NetworkX Edge Colormap:

http://networkx.github.io/documentation/latest/examples/drawing/edge_colormap.html

and here is the source code:

    #!/usr/bin/env python
"""
Draw a graph with matplotlib, color edges.
You must have matplotlib>=87.7 for this to work.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
try:
    import matplotlib.pyplot as plt
except:
    raise

import networkx as nx

G=nx.star_graph(20)
pos=nx.spring_layout(G)
colors=range(20)
nx.draw(G,pos,node_color='#A0CBE2',edge_color=colors,width=4,edge_cmap=plt.cm.Blues,with_labels=False)
plt.savefig("edge_colormap.png") # save as png
plt.show() # display

After playing around with their source code, I can't figure out how to hardcode distance of the edge circles from the centre. Right now its random.

Also how do I label the edge circles and their distance from the centre?

I know for position comes from pos=nx.spring_layout(G). So I looked at the spring_layout attribute and found that position can be specified by using a pos variable which is a dictionary with nodes as keys and values as a list. (https://networkx.github.io/documentation/latest/reference/generated/networkx.drawing.layout.spring_layout.html)

But even when I do the following result is random edges :

ap = {'uniwide':[55,34,1],'eduram':[34],'uniwide_webauth':[20,55,39],'uniwide_guest':[55,34],'tele9751_lab':[100],'HomeSDN':[100],'TP-LINK':[39]}

pos=nx.spring_layout(G,pos=ap)  

回答1:

You can set the node positions explicitly with the pos dictionary. For example

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge('center',1)
G.add_edge('center',2)
G.add_edge('center',3)
G.add_edge('center',4)

pos = {'center':(0,0),
       1:(1,0),
       2:(0,1),
       3:(-1,0),
       4:(0,-1)
       }

nx.draw(G, pos=pos, with_labels=True)
plt.show()



回答2:

I'm trying to be as helpful as I can. I wouldn't try to keep them static. You'll want to add and remove things, and the algorithm's automatic placement is something you don't want to lose. According to the docs, you should probably tweak k. It looks like n is 20, so multiply k times some factor to increase the distance.

n = 20
nx.spring_layout(G, k=(1.0/pow(n, .5))) # what it currently is

should maybe be this:

nx.spring_layout(G, k=(1.0/pow(n, .5))*1.5) # play around with this factor