Reputation: 1143
I am trying to draw a graph using NetworkX in Python. I am using the following code:
G=nx.to_networkx_graph(adj)
pos=nx.spring_layout(G)
#G=nx.path_graph(8)
nx.draw(G,pos,labels)
plt.savefig("simple_path.png") # save as png
plt.show() # display
I get this output:
But I want to get the following output with Labels:
What can I do on the code? thank you.
Upvotes: 1
Views: 2971
Reputation: 23887
So for the positioning, you've set pos
based on spring_layout
. pos
gives the positions of your nodes. Check it out - once you've defined it, ask python to print pos
for you and see what it's doing.
Here's an alternative code:
import networkx as nx
import pylab as py
blue_edges = [('B', 'C'), ('B', 'D'), ('B', 'E'), ('E', 'F')]
red_edges = [('A', 'B'), ('A', 'C'), ('C', 'E'), ('D', 'E'), ('D', 'F')]
G=nx.Graph() #define G
G.add_edges_from(blue_edges)
G.add_edges_from(red_edges)
pos = {'A':(0,0), 'B':(1,1), 'C':(1,-1), 'D':(2,1), 'E':(2,-1), 'F':(3,0)}
nx.draw_networkx(G, pos=pos, edgelist = [], node_color = 'k')
nx.draw_networkx(G, pos=pos, nodelist = [], edgelist = blue_edges, edge_color = 'b')
nx.draw_networkx(G, pos=pos, nodelist = [], edgelist = red_edges, edge_color = 'r')
and if you want it without the x and y axes showing, change the last bit to:
nx.draw(G, pos=pos, edgelist = [], node_color = 'k')
nx.draw(G, pos=pos, nodelist = [], edgelist = blue_edges, edge_color = 'b')
nx.draw(G, pos=pos, nodelist = [], edgelist = red_edges, edge_color = 'r')
Upvotes: 4