How can one modify the outline color of a node In networkx?

人盡茶涼 提交于 2019-12-04 23:03:04

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'.

Since NetworkX 2.1, there's an edgecolors argument added to draw_networkx_nodes()(as well as to draw() since it ultimately calls draw_networkx_nodes() to draw nodes).

If you want to change the color of the nodes' outline, you can just do:

draw(G, linewidths=2)
ax = plt.gca() # to get the current axis
ax.collections[0].set_edgecolor("#FF0000") 

And that's it.

  • ax.collections[0] is a PathCollection object governing the nodes
  • ax.collections[1] is a LineCollection object governing the edges if you have some.

You can modify many other properties rapidly with a given collection.

I know this is an antient thread, but I was looking for this answer too, and finally found the native non-hacky way. You can pass the argument linewidths=0 into the draw function. I think this only affects the width of the node borders rather than the edge width (which is controled by width=x).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!