在networkx中创建输入箭头

时间:2018-03-06 21:09:00

标签: python graph networkx

我想知道是否有可能创建某种符号来表示networkx / Python中图形的输入。

例如,拍摄显示的图像here,假设我希望能够识别来源和接收器。我有兴趣创建一个表示,如:

enter image description here

这可能吗?

1 个答案:

答案 0 :(得分:1)

annotate功能完全符合您的要求。 (另见annotate intro

根据您链接的示例,您可以添加以下内容来注释所选节点。 (这取决于位置字典pos以了解节点的位置。)

ax = plt.gca()
ax.annotate("3", xy=pos.get('B'), xytext=(0, 40), textcoords='offset points',
    arrowprops=dict(facecolor='black', shrink=0.15),  
    bbox=dict(boxstyle="round", fc="cyan"))
ax.annotate("4", xy=pos.get('F'), xytext=(0, 40), textcoords='offset points',
    arrowprops=dict(facecolor='black', shrink=0.15),
    bbox=dict(boxstyle="round", fc="cyan"))

example networkx with annotation

这个答案是自包含的,完整代码包括linked example

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}
values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), 
                       node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)

# add annotations for selected nodes.
ax = plt.gca()
ax.annotate("3", xy=pos.get('B'), xytext=(0, 40), textcoords='offset points',
        arrowprops=dict(facecolor='black', shrink=0.15),  
        bbox=dict(boxstyle="round", fc="cyan"))
ax.annotate("4", xy=pos.get('F'), xytext=(0, 40), textcoords='offset points', 
        arrowprops=dict(facecolor='black', shrink=0.15),  
        bbox=dict(boxstyle="round", fc="cyan"))

plt.show()