我正在使用networkx来绘制一个在给定场地上具有节点位置的网络图。该场地被分成一定数量的格子,而节点位置对应着一个格子。在绘制图表时,我希望在背景中显示一个网格,以便在图表中可以看到单元格和距离。networkx是否提供这样的选项?我没有找到相关内容。我尝试通过pyplot设置网格:
plt.xlim(0,14)
plt.ylim(0,10)
plt.xticks([x for x in xrange(0,14)])
plt.yticks([x for x in xrange(0,10)])
plt.grid(True)
这个程序可以独立运行(详见这里),但是同时也可以被调用。
nx.draw(G, pos)
它展示了没有网格的图形(见这里)。我猜想网格仍然在背景中,但networkx完全覆盖了它。
那么有没有办法使用plt显示网格,或者可能是我没发现的允许类似操作的networkx命令?
编辑:这是使用的完整代码。看看取消/注释nx.draw(G, pos)
时的差异。
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
def quit_figure(event):
if event.key == 'q':
plt.close(event.canvas.figure)
nodes = [[1,1],[3,1],[6,1],[3,2],[13,1],[3,5]]
distance_array = [
[[],[],[1,3],[],[5],[],[],[],[],[],[],[],[],[],[]],
[[],[3],[0],[2],[],[],[],[],[],[],[],[],[],[],[]],
[[],[],[],[1,3],[5],[],[],[4],[],[],[],[],[],[]],
[[],[1],[0],[2,5],[],[],[],[],[],[],[10],[],[],[],[]],
[[],[],[],[],[],[],[],[2],[],[],[3,5],[],[],[],[]],
[[],[],[],[3],[0,2],[],[],[],[],[],[4],[],[],[],[],[]],
[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]],
[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]],
[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]]
current_transmission_range = 0
transmission_range = np.zeros((len(nodes)), dtype=int)
pos = {x:[nodes[x][0],nodes[x][1]] for x in xrange(len(nodes))}
graph_nodes = [x for x in xrange(len(nodes))]
current_transmission_range = 0
cid = plt.gcf().canvas.mpl_connect('key_press_event', quit_figure)
plt.xlim(0,14)
plt.ylim(0,10)
plt.xticks([x+0.5 for x in xrange(0,14)], [' '+str(x) for x in xrange(0,13)])
plt.yticks([x+0.5 for x in xrange(0,10)], ['\n\n'+str(x)+'\n\n\n\n' for x in xrange(0,9)])
plt.grid(True)
G = nx.Graph()
for node in graph_nodes:
G.add_node(node)
for node in graph_nodes:
for j in xrange(transmission_range[node]+1):
for k in distance_array[node][j]:
if(j <= current_transmission_range):
G.add_edge(node, k,weight=j)
edge_weight=dict([((u,v,),int(d['weight'])) for u,v,d in G.edges(data=True)])
nx.draw_networkx_edge_labels(G, pos,edge_labels=edge_weight)
# draw graph
# nx.draw(G, pos)
plt.show()
hold
参数吗? - loopbackbeeax
参数,那应该会有所帮助。只需要弄清楚具体怎么做就行了。 - Simon