Reproduce same graph in NetworkX

笑着哭i 提交于 2021-01-27 19:13:42

问题


I would like to improve my graph. There are problems as follow:

  1. how to create a consistent graph.the graph itself is not consistent everytime i execute / run the code, it will generate different images. The inconsistent graph is shown in the url.

  1. how to customize the whole graph / picture size and to make it bigger
  2. how to set a permanent position for an object 'a' so that it will consistently appears at the first / top position
  3. how to customize length of arrow for each relationship.

Appreciate if anyone could give some notes or advices

This is my codes:

Unique_liss= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

edgesList= [('a', 'b'), ('b', 'c '), ('c ', 'd'), ('d', 'e'), ('d', 'f'), ('e', 'g'), ('f', 'g'), ('g', 'h'), ('h', 'i '), ('i ', 'j'), ('j', 'k'), ('j', 'l'), ('k', 'm'), ('l', 'm')]

import networkx as nx
g = nx.DiGraph()
g.add_nodes_from(Unique_liss)
g.add_edges_from(edgesList)
nx.to_pandas_adjacency(g)

G = nx.DiGraph()
for node in edgesList:
    G.add_edge(*node,sep=',')

A = nx.adjacency_matrix(G).A

nx.draw(G, with_labels=True, node_size = 2000,
        node_color = 'skyblue')

回答1:


In order to have deterministic node layouts, you can use one of NetworkX's layouts, which allow you to specify a seed. Here's an example using nx.spring_layout for the above graph:

from matplotlib import pyplot as plt

seed = 31
pos = nx.spring_layout(G, seed=seed)
plt.figure(figsize=(10,6))
nx.draw(G, pos=pos, with_labels=True, node_size = 1500,
        seed=seed, node_color = 'skyblue')

You'll get the exact same layout if you re-run the above.

In order to customize the graph size you have several options. The simplest one baing setting the figure size as plt.figure(figsize=(x,y)) as above. And you can also control the size of the graph within the figure using the scale paramater in nx.spring_layout.

As per the last point, it looks like you cannot set specific arrow sizes for each edge. From the [docs](arrowsize : int, optional (default=10)) what you have is:

arrowsize : int, optional (default=10)

So you can only set this value to an int, which will result in an equal size for all edge arrows.



来源:https://stackoverflow.com/questions/62062012/reproduce-same-graph-in-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!