networkx draw_networkx_edges capstyle

2019-04-28 20:48发布

问题:

Does anyone know if it is possible to have fine-grained control over line properties when drawing networkx edges via (for example) draw_networkx_edges? I would like to control the line solid_capstyle and solid_joinstyle, which are (matplotlib) Line2D properties.

>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G = nx.dodecahedral_graph()
>>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G), width=7)
>>> plt.show()

In the example above, there are 'gaps' between the edges which I'd like to hide by controlling the capstyle. I thought about adding the nodes at just the right size to fill in the gaps, but the edges in my final plot are coloured, so adding nodes won't cut it. I can't figure out from the documentation or looking at edges.properties() how to do what I want to do... any suggestions?

Carson

回答1:

It looks like you can't set the capstyle on matplotlib line collections.

But you can make your own collection of edges using Line2D objects which allows you to control the capstyle:

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
G = nx.dodecahedral_graph()
pos = nx.spring_layout(G)
ax = plt.gca()
for u,v in G.edges():
    x = [pos[u][0],pos[v][0]]
    y = [pos[u][1],pos[v][1]]
    l = Line2D(x,y,linewidth=8,solid_capstyle='round')
    ax.add_line(l)
ax.autoscale()
plt.show()