使用python的matplotlib与networkx绘制网络分面图
数据格式:
左边两列是网络的ID与name 再右边变是网络的连边了。比如第一行网络的边为(1,2)(3,4)(2,3)(4,5)
代码:
# coding: utf-8
import networkx as nx
import matplotlib.pyplot as plt
import csv
def LoadData():
UnitedVisibilityGraphDictData=csv.reader(file('UnitedVisibilityGraphDict.csv', 'rb'))
UnitedVisibilityGraphDict={}
count=0 #don't read first line
for data in UnitedVisibilityGraphDictData:
edges=[]
if count!=0:
count2=2
for i in range(len(data)/2-1):
if len(data[count2])!=0:
medium=(int(data[count2]),int(data[count2+1]))
edges.append(medium)
count2+=2
UnitedVisibilityGraphDict[data[0]]=edges
count+=1
#print UnitedVisibilityGraphDict['1'] #test code
#print UnitedVisibilityGraphDict['4']
return UnitedVisibilityGraphDict
def DrawVisibilityGraphDict(UnitedVisibilityGraphDict):
graphList=[]
for i in range(1,len(UnitedVisibilityGraphDict)+1):
G=nx.Graph()
G.add_edges_from(UnitedVisibilityGraphDict[str(i)])
graphList.append((i,G)) #i is int type ,G is class type
fig=plt.figure(figsize=(20,16))
#plt.clf()#clear canvas
for i in range(1,26):
ax=fig.add_subplot(5,5,i)
ax.set_xticks([])
ax.set_yticks([])
ax.set_ylim([-0.2,1.2])
plt.title('Visibility Graph State %d'%(graphList[i-1][0]))
#nx.draw(graphList[i-1][1],pos,node_size=150,with_labels=True) #this method can draw the picture without frame
pos=nx.spring_layout(graphList[i-1][1],iterations=30)
nx.draw_networkx_nodes(graphList[i-1][1],pos,node_size=400)
nx.draw_networkx_edges(graphList[i-1][1],pos,width=2)
nx.draw_networkx_labels(graphList[i-1][1],pos,font_size=20,font_family='sans-serif')
plt.savefig("outputResult/VisibilityGraphDict2.png")
plt.show()
if __name__=="__main__":
UnitedVisibilityGraphDict=LoadData()
DrawVisibilityGraphDict(UnitedVisibilityGraphDict)
结果: