使用 matplotlib 绘制图形 python
Plotting graph using matplotlib python
我需要为 ACO TSP 的以下解绘制图形。我需要绘制的图表将接近于此:
有任何我可以处理的代码片段吗?
来自 tsplib95 的文档:
Converting problems
get_graph() creates a networkx.Graph instance from the problem data:
>>> G = problem.get_graph()
>>> G.nodes
NodeView((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
所以,G是一个networkx
图,也就是说你可以用networkx
来画它:
import matplotlib.pyplot as plt
import networkx as nx
nx.draw_networkx(G)
plt.show()
编辑:绘制路径:
pos = nx.spring_layout(G)
H = nx.DiGraph(G) # convert to directed graph s.t. the edges have arrows.
nx.draw_networkx_nodes(H, pos=pos) # draw nodes
nx.draw_networkx_edges(H, pos=pos, alpha=0.1) # draw all edges with transparency
nx.draw_networkx_edges(H, pos=pos, edgelist=tour.path, edge_color='red') # highlight the edges in the path
plt.show()
我需要为 ACO TSP 的以下解绘制图形。我需要绘制的图表将接近于此:
有任何我可以处理的代码片段吗?
来自 tsplib95 的文档:
Converting problems get_graph() creates a networkx.Graph instance from the problem data: >>> G = problem.get_graph() >>> G.nodes NodeView((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
所以,G是一个networkx
图,也就是说你可以用networkx
来画它:
import matplotlib.pyplot as plt
import networkx as nx
nx.draw_networkx(G)
plt.show()
编辑:绘制路径:
pos = nx.spring_layout(G)
H = nx.DiGraph(G) # convert to directed graph s.t. the edges have arrows.
nx.draw_networkx_nodes(H, pos=pos) # draw nodes
nx.draw_networkx_edges(H, pos=pos, alpha=0.1) # draw all edges with transparency
nx.draw_networkx_edges(H, pos=pos, edgelist=tour.path, edge_color='red') # highlight the edges in the path
plt.show()