###前提・実現したいこと
以下の画像のように経路問題を図示したいです
(番号はついてなくてもいいです)
辺は以下のように格納されています
python
1#全部の辺 2lines = set(range(0,12)) 3#経路として選択された辺 4selected_lines = {2,5,8,11}
###試したこと
graphviz
matplotlib
pillow
を見ましたが、格子状かつ辺ごとに選択できる
記述の仕方が分かりませんでした
###補足情報(言語/FW/ツール等のバージョンなど)
python3.6
###解決後 まとめ
networkx
を用いることで容易に経路の図示ができました
回答して頂いたコードを以下のように変更しました
- 選択された経路の色を変更
- 経路の番号の表示
python
1import matplotlib.pyplot as plt 2import networkx as nx 3 4point_num = 3 5line_num = point_num - 1 6G = nx.grid_graph([point_num, point_num]) 7pos = dict((n, n) for n in G.nodes()) 8 9edge_num = point_num * line_num * 2 10colors = ['k' for _ in range(edge_num)] # default color is black (k) 11selected_edges_index = [0,5,10,11] 12for index in selected_edges_index: 13 colors[index] = 'r' #change edge color to red 14 15nx.draw_networkx_edge_labels(G, pos,{ 16 edge:i for (i,edge) in enumerate(G.edges) #add number of edge 17}) 18nx.draw(G,pos,edge_color=colors,font_size=8) 19plt.savefig("grid.png") 20
追記1
選択経路を色を変えて、表現するのは
networkx
においてナンセンスだと思い直したので変更
変更したことでnx.connected_components(G)
で正しく連結成分を
利用することができます
以下のように変更
- 経路ではないedgeは表示しない
python
1import matplotlib.pyplot as plt 2import networkx as nx 3 4point_num = 3 5line_num = point_num - 1 6edge_num = point_num * line_num * 2 7selected_edges_index = [0,5,10,11] 8 9G = nx.grid_graph([point_num, point_num]) 10edges_copy = list(G.edges) 11pos = dict((n, n) for n in G.nodes()) 12nx.draw_networkx_edge_labels(G, pos,{ 13 edge:i for (i,edge) in enumerate(G.edges) #add number of edge 14}) 15G.remove_edges_from(list(G.edges)) # remove all edges 16 17for i in selected_edges_index: 18 G.add_edge(edges_copy[i][0],edges_copy[i][1]) 19nx.draw(G,pos,font_size=8) 20 21#plt.savefig("grid.png") 22plt.show() 23
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。