How can one modify the outline color of a node In networkx?
UPDATE (3/2019): as of networkx 2.1, the kwargs are forwarded from draw()
, so you should be able to simply call draw()
with the edge_color
kwarg.
Ok, this is kind of hacky, but it works. Here's what I came up with.
The Problem
networkx.draw()
calls networkx.draw_networkx_nodes()
, which then calls pyplot.scatter()
to draw the nodes. The problem is that the keyword args accepted by draw_networkx_nodes()
aren't passed on to scatter()
. (source here)
To solve this, I basically broke apart networkx.draw()
into its components: draw_networkx_nodes
, draw_networkx_edges
, and draw_networkx_labels
.
The Solution
We can take the return value of draw_networkx_nodes()
-- a PathCollection
-- and operate on that: you can use PathCollection.set_edgecolor()
or PathCollection.set_edgecolors()
with either a color or a list, respectively.
Example code:
from networkx import *
import matplotlib.pyplot as plt
G = Graph()
G.add_node(1)
# Need to specify a layout when calling the draw functions below
# spring_layout is the default layout used within networkx (e.g. by `draw`)
pos = spring_layout(G)
nodes = draw_networkx_nodes(G, pos)
# Set edge color to red
nodes.set_edgecolor('r')
draw_networkx_edges(G, pos)
# Uncomment this if you want your labels
## draw_networkx_labels(G, pos)
plt.show()
If you're going to be using this a lot, it probably makes more sense (IMO) to just redefine draw_networkx_nodes
to actually pass the kwargs to scatter
. But the above will work.
To remove the marker edges entirely, simply set the color to None
instead of 'r'
.
Networkx, changing node colors
Something like this could works:
import networkx as nx
import matplotlib.pyplot as plt
M = nx.erdos_renyi_graph(10, 2)
color = []
for node in M:
if node > 1:
color.append('red')
else:
color.append('green')
nx.draw(M, node_color=color)
plt.show()
Here the application with your example
import numpy as np
import matplotlib.pyplot as plt
from random import randint
import networkx as nx
N = 10 #Lattice Size
#Random Coordinate Generator
def random(m, n):
seen = set()
x, y = randint(m, n), randint(m, n)
while True:
seen.add((x, y))
yield (x, y)
x, y = randint(m, n), randint(m, n)
while (x, y) in seen:
x, y = randint(m, n), randint(m, n)
#Generates Lattice
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = nx.get_node_attributes(G, 'status')
G.add_nodes_from(G.nodes,status='1')
#Change Node attribute
num_nodes=N*N
half=int(num_nodes/2)
decaying = [0]*half
a=random(0,N-1)
for i in range(half):
cor=next(a)
decaying[i]=cor
for j in range(half):
a=decaying[j]
G.add_node(a, status='0')
node_color = []
for status in list(nx.get_node_attributes(G, 'status').values()):
if status == '1':
node_color.append('red')
else:
node_color.append('green')
#Plot nodes
labels = nx.get_node_attributes(G, 'status')
nx.draw(G,pos=pos,node_color=node_color, labels=labels,node_size=200)
plt.show()
Change Edge color in NetworkX Graph depending on what edges has been visisted by Dijkstras algorithm
Try adding edge_color
to nx.draw()
import networkx as nx
import matplotlib.pyplot as plt
G = nx.karate_club_graph()
nodes = G.nodes()
position = nx.spring_layout(G)
color = {"Mr. Hi": "#3DA3F5", "Officer": "#E0D91B"}
dijkstra_route = nx.dijkstra_path(G, 24, 16)
colors = ["red" if n in dijkstra_route else color[G.nodes[n]["club"]] for n in nodes]
dijkstra_edges = []
for index in range(0, len(dijkstra_route) - 1):
edge = (dijkstra_route[index], dijkstra_route[index + 1])
dijkstra_edges.append(edge)
edge_colors = ["red" if edge in dijkstra_edges else "black" for edge in G.edges()]
nx.draw(G, position, node_color=colors, edge_color=edge_colors, with_labels=True)
plt.show()
shows this, which is close to what you want, although I can't figure out why edge (31,0)
isn't colored
Coloring specific nodes in networkx
You can draw your nodes in groups based on color similar to the example they provide. With each group that you draw, just specify node_color
to the color that you want.
import networkx as nx
G = nx.cubical_graph()
pos = nx.spring_layout(G)
nodes = {
'r': [1, 3, 5],
'b': [0, 2],
'g': [4]
}
for node_color, nodelist in nodes.items():
nx.draw_networkx_nodes(G, pos, nodelist=nodelist, node_color=node_color)
labels = {x: x for x in G.nodes}
nx.draw_networkx_labels(G, pos, labels, font_size=16, font_color='w')
Python NetworkX -- set node color automatically based on number of attribute options
Here is an example of how to use a colormap. It's a little tricky. If you want a customized discrete colormap you can try this SO answer Matplotlib discrete colorbar
import matplotlib.pyplot as plt
# create number for each group to allow use of colormap
from itertools import count
# get unique groups
groups = set(nx.get_node_attributes(g,'group').values())
mapping = dict(zip(sorted(groups),count()))
nodes = g.nodes()
colors = [mapping[g.node[n]['group']] for n in nodes]
# drawing nodes and edges separately so we can capture collection for colobar
pos = nx.spring_layout(g)
ec = nx.draw_networkx_edges(g, pos, alpha=0.2)
nc = nx.draw_networkx_nodes(g, pos, nodelist=nodes, node_color=colors,
with_labels=False, node_size=100, cmap=plt.cm.jet)
plt.colorbar(nc)
plt.axis('off')
plt.show()
Related Topics
Looping in Python: Modify One Column Based on Values in Other Columns
Multiprocessing: How to Use Pool.Map on a Function Defined in a Class
How to Sort a List of Lists by a Specific Index of the Inner List
How to Properly Setup Pipenv in Pycharm
Valueerror: Invalid \Escape Unable to Load Json from File
List of the Most Recently Updated Files in Python
How to Read Image Data from a Url in Python
Using Buttons in Tkinter to Navigate to Different Pages of the Application
Python - How to Check If Table Exists
Pickle - Cpickle.Unpicklingerror: Invalid Load Key, '?'
How to Further Filter a Result of Resultset
Pandas - Calculate Average of Columns With Condition Based on Values in Other Columns
Why Does Tkinter Image Not Show Up If Created in a Function
Importerror: No Module Named Psycopg2 After Install
Get Absolute Paths of All Files in a Directory
How to Get the Current Ipython/Jupyter Notebook Name
How to Enable Autocomplete (Intellisense) for Python Package Modules