最近需要繪制基因調控網絡,選擇了python語言中比較popular的networkx包,先上目前結果圖:
節點是基因或者其他實體,邊代表調控關系,黑色的邊代表抑制,紅色的邊代表激活,紅色的節點代表自我激活,黑色的節點代表自我抑制。
繪制的關鍵點:邊可以有不同的顏色,指向符號可以修改,可以繪制出自循環的邊(self-loop)
本來抑制的邊用截止符號-[更好,但是發現有時候看不清是來自哪條邊的,所以就都改成箭頭了,用顏色來區別關系;然后花了n久來找怎么繪制自循環的邊,發現networkx的draw相關的方法 (基於matplotlib) 並不能顯示(雖然我定義了節點n到節點n的邊,但是結果不顯示),查了一大堆發現確實是不支持的,好像說難實現還是咋回事...目前我已知的解決辦法就是用另外一個繪圖包graphviz,如該鏈接問題:https://stackoverflow.com/questions/49340520/matplotlib-and-networkx-drawing-a-self-loop-node
(networkx的繪圖包)
我試了一下,確實可以,但效果沒有之前好,所以決定換一種思路,用顏色代表自循環吧,用graphviz結果如下:
目前結果的代碼如下:
1 import networkx as nx 2 import matplotlib.pyplot as plt 3 4 with open('grn_sample.txt', 'r', encoding='UTF-8') as fread: 5 cont = fread.readlines() 6 contLines = [] 7 genes = set() 8 G = nx.MultiDiGraph() 9 pEdges = [] 10 nEdges = [] 11 for line in cont: 12 tmp = line.strip().split(' ') 13 genes.add(tmp[0]) 14 genes.add(tmp[1]) 15 contLines.append(tmp) 16 genes = list(genes) 17 selfActGenes=set() 18 selfInhGenes=set() 19 G.add_nodes_from(genes) 20 for edge in contLines: 21 row = genes.index(edge[0]) 22 col = genes.index(edge[1]) 23 if edge[2] == '+': 24 pEdges.append((edge[0], edge[1])) 25 if row==col: 26 selfActGenes.add(edge[0]) 27 elif edge[2] == '-': 28 nEdges.append((edge[0], edge[1])) 29 if row==col: 30 selfInhGenes.add(edge[0]) 31 else: 32 print('Unsupported regulatory relationship.') 33 selfActGenes=list(selfActGenes) 34 selfInhGenes=list(selfInhGenes) 35 # show grn by network visualization 36 G.add_edges_from(pEdges) 37 G.add_edges_from(nEdges) 38 pos=nx.spring_layout(G) # 很重要! 39 nx.draw_networkx_nodes(G,pos,node_color='lightblue') # initial colors for all nodes 40 nx.draw_networkx_nodes(G, pos, nodelist=selfActGenes, node_color='red') # self-active nodes with red colors 41 nx.draw_networkx_nodes(G, pos, nodelist=selfInhGenes, node_color='black') # self-inhibited nodes with black colors 42 nx.draw_networkx_labels(G,pos) 43 nx.draw_networkx_edges(G,pos,edgelist=pEdges,edge_color='red',connectionstyle='arc3,rad=0.2',arrowsize=18) 44 nx.draw_networkx_edges(G, pos, edgelist=nEdges, edge_color='black',arrows=True,connectionstyle='arc3,rad=0.2',arrowsize=18) 45 plt.show()
讀入文件如下(僅僅定義邊):
如果你需要使用截止符號,只需要在draw邊的函數中定義參數arrowstyle,具體可以看官方文檔,非常清晰: https://networkx.github.io/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw_networkx_edges.html
P.S. 對了,這次根據所需效果查詢發現了直接看查詢結果中圖片結果的好處,可以通過圖片直觀的找到你要的效果所在的網頁,節省很多時間。