I have the following code
#!/usr/bin/python
import sys
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph();
G.add_node('A')
G.add_node('B')
G.add_node('C')
G.add_node('D')
G.add_edge('A','B',weight=1)
G.add_edge('C','B',weight=1)
G.add_edge('B','D',weight=30)
colors=range(20)
nx.draw_spring(G,font_size=20,width=2,node_size=1000,node_color='#A0CBE2')
plt.savefig("/Users/handsomeguy/Desktop/test.png",dpi=300)
That generate the following graph (without the comment of course):
As stated in the picture above. I'd like to change the color of node C
and D
and enlarge the size of these chosen nodes. How can I achieve that?
Note that C and D are predetermined nodes by me the user.
One easy way to change the style of individual nodes when you have a small graph is to pass the parameters (eg node_size
or node_color
) of networkx.draw_spring
lists of sizes/colors. The trick is that if you use a list, the list has to include a size/color for each node , and the list has to be in the same order as the G.nodes()
(hence why I sort
the nodes in the example below):
nx.draw_spring(G, nodelist=sorted(G.nodes()), font_size=20, width=2,
node_size=[1000, 1000, 2000, 3000],
node_color=["#A0CBE2", "#A0CBE2", "#FF0000", "#FFFF00"])
And here's the result:
Another option is to is to first store the layout of the nodes/edges for your graph, and then use networkx.draw_networkx
. This is probably more useful when you have a large graph and only want to change the style for a few nodes. Here, I first store the spring layout for the graph in pos
, and then pass pos
to draw each of the nodes and their edges:
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos, nodelist=["A", "B"], node_size=1000, node_color='#A0CBE2', font_size=20, width=2)
nx.draw_networkx(G, pos=pos, nodelist=["C"], node_size=2000, node_color='#FF0000', font_size=20, width=2,)
nx.draw_networkx(G, pos=pos, nodelist=["D"], node_size=3000, node_color='#FFFF00', font_size=20, width=2)
Note : to turn off the axis in the networkx.draw_networkx
plot, add the following command before plt.show()
:
limits=plt.axis('off')
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.