Reputation: 24774
I draw a graph with networkx and draw_circular
networkx.draw_circular(g)
I try change the color of some nodes, maybe with draw_networkx_nodes.
but for this, I need know the node position, how I can get the position of nodes in draw_circular ?
or directly, how I can change the color of some nodes in draw_circular?
Upvotes: 1
Views: 10658
Reputation: 305
Just to add to the previous answer (Avaris), using "nodelist" attribute of "networkx.draw_networkx_nodes()" might be useful as well .
import matplotlib.pyplot as plt
import networkx as nx
nodes = [0,1,2,3]
edges = [(0,1), (1,2), (3,1), (2,3)]
nodeListA = [0,1]
nodeListB = [2,3]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
position = nx.circular_layout(G)
nx.draw_networkx_nodes(G,position, nodelist=nodeListA, node_color="b")
nx.draw_networkx_nodes(G,position, nodelist=nodeListB, node_color="r")
nx.draw_networkx_edges(G,position)
nx.draw_networkx_labels(G,position)
plt.show()
This generates the following figure:
You can also access the positions of the nodes from the variable "position". The output would look something like this:
In [119]: position
Out[119]:
{0: array([ 1. , 0.5], dtype=float32),
1: array([ 0.49999997, 1. ], dtype=float32),
2: array([ 0. , 0.49999997], dtype=float32),
3: array([ 0.5, 0. ], dtype=float32)}
Upvotes: 2
Reputation: 36715
draw_circular
will accept keyword arguments same as draw_networkx
. There is an optional argument node_color
where you can supply colors for individual nodes. Argument passed to node_color
must be a list with the length as number of nodes or a single value that will be used for all nodes. Color can be anything that is recognized by matplotlib.
So something like this would give the result below:
import networkx as nx
import matplotlib.pyplot as plt
from random import random
g = nx.random_graphs.erdos_renyi_graph(10,0.5)
colors = [(random(), random(), random()) for _i in range(10)]
nx.draw_circular(g, node_color=colors)
plt.show()
Edit
Optinoally, you can get the positions of nodes for certain layout with the networkx.layout.circular_layout
, etc..
Upvotes: 7