I have the following lists:
l1=["a", "a", "c", "d", "e", "f", "g", "h", "i"]
l2=["1", "2", "3", "4", "5", "6", "7", "8", "9"]
l3=["A", "B", "C", "D", "E", "F", "G", "H", "I"]
l4=[12, 14, 22, 33, 44, 55, 66, 77, 88]
l=[l1, l2, l3, l4]
And I want to create and draw a networkx graph from these lists with a given number of nodes, such that there is an edge between the elements of the same list. In the example above, assuming the number of nodes is 20, the graph nodes should be:
(('a'), ('1'), ('A'), (12), ('c'), ('3'), ('C'), (22), ('d'), ('4'), ('D'), (33))
Without taking into account ('a'), ('2'), ('B'), (14)
because there is already a node 'a'. Therefore, the other lists' elements in the same position must not be considered. The graph edges should be:
(['a', 'c'], ['c', 'd'], ['d', 'e'], ['e', 'f'],
['1', '3'], ['3', '4'], ['4', '5'], ['5', '6'],
['A', 'C'], ['C', 'D'], ['D', 'E'], ['E', 'F'],
[12, 22], [22, 33], [33, 44], [44, 55])
These edges must be vertical. I wrote the following code:
import networkx as nx
G=nx.Graph()
for j in range(int(20/len(l))):
for i in range(len(l)):
if G.number_of_nodes()<20:
G.add_node(l[i][j], pos=(i*2, j))
if j>0 and l[i][j]!=l[i][j-1]:
G.add_edge(l[i][j], l[i][j-1])
But it seems it doesn't work properly. The nodes and edges' lists I got are:
NodeView(('a', '1', 'A', 12, '2', 'B', 14, 'c', '3', 'C', 22, 'd', '4', 'D', 33, 'e', '5', 'E', 44))
EdgeView([('a', 'c'), ('1', '2'), ('A', 'B'), (12, 14), ('2', '3'), ('B', 'C'), (14, 22), ('c', 'd'), ('3', '4'), ('C', 'D'), (22, 33), ('d', 'e'), ('4', '5'), ('D', 'E'), (33, 44)])
The edges list is not like I described above. Any help will be appreciated
import networkx as nx
def create_graph(l):
G=nx.Graph()
for j in range(len(l[0])):
if l[0][j] in G.nodes:
continue
for i in range(len(l)):
if G.number_of_nodes() >= 20:
return G
G.add_node(l[i][j], pos=(i*2, j))
if j>0 and l[i][j]!=l[i][j-1]:
G.add_edge(l[i][j], l[i][j-1])
l1=["a", "a", "c", "d", "e", "f", "g", "h", "i"]
l2=["1", "2", "3", "4", "5", "6", "7", "8", "9"]
l3=["A", "B", "C", "D", "E", "F", "G", "H", "I"]
l4=[12, 14, 22, 33, 44, 55, 66, 77, 88]
l=[l1, l2, l3, l4]
G = create_graph(l)
print(G.nodes)
print(G.edges)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.