python-plot and networkx繪制網絡關系圖


1、用matplotlib繪制網絡圖  

基本流程:
  1. 導入networkx,matplotlib包
  2. 建立網絡
  3. 繪制網絡 nx.draw()
  4. 建立布局 pos = nx.spring_layout美化作用

最基本畫圖程序

import import networkx as nx             #導入networkx包
import matplotlib.pyplot as plt 
G = nx.random_graphs.barabasi_albert_graph(100,1)   #生成一個BA無標度網絡G
nx.draw(G)                               #繪制網絡G
plt.savefig("ba.png")           #輸出方式1: 將圖像存為一個png格式的圖片文件
plt.show()                            #輸出方式2: 在窗口中顯示這幅圖像 

2、networkx 提供畫圖的函數有:

  1. draw(G,[pos,ax,hold])
  2. draw_networkx(G,[pos,with_labels])
  3. draw_networkx_nodes(G,pos,[nodelist]) 繪制網絡G的節點圖
  4. draw_networkx_edges(G,pos[edgelist]) 繪制網絡G的邊圖
  5. draw_networkx_edge_labels(G, pos[, ...]) 繪制網絡G的邊圖,邊有label
    ---有layout 布局畫圖函數的分界線---
  6. draw_circular(G, **kwargs) Draw the graph G with a circular layout.
  7. draw_random(G, **kwargs) Draw the graph G with a random layout.
  8. draw_spectral(G, **kwargs) Draw the graph G with a spectral layout.
  9. draw_spring(G, **kwargs) Draw the graph G with a spring layout.
  10. draw_shell(G, **kwargs) Draw networkx graph with shell layout.
  11. draw_graphviz(G[, prog]) Draw networkx graph with graphviz layout.

3、networkx 畫圖參數:
node_size: 指定節點的尺寸大小(默認是300,單位未知,就是上圖中那么大的點)
node_color: 指定節點的顏色 (默認是紅色,可以用字符串簡單標識顏色,例如'r'為紅色,'b'為綠色等,具體可查看手冊),用“數據字典”賦值的時候必須對字典取值(.values())后再賦值
node_shape: 節點的形狀(默認是圓形,用字符串'o'標識,具體可查看手冊)
alpha: 透明度 (默認是1.0,不透明,0為完全透明)
width: 邊的寬度 (默認為1.0)
edge_color: 邊的顏色(默認為黑色)
style: 邊的樣式(默認為實現,可選: solid|dashed|dotted,dashdot)
with_labels: 節點是否帶標簽(默認為True)
font_size: 節點標簽字體大小 (默認為12)
font_color: 節點標簽字體顏色(默認為黑色)
e.g. nx.draw(G,node_size = 30, with_label = False)
繪制節點的尺寸為30,不帶標簽的網絡圖。


4、布局指定節點排列形式

pos = nx.spring_layout 

建立布局,對圖進行布局美化,networkx 提供的布局方式有:
- circular_layout:節點在一個圓環上均勻分布
- random_layout:節點隨機分布
- shell_layout:節點在同心圓上分布
- spring_layout: 用Fruchterman-Reingold算法排列節點(這個算法我不了解,樣子類似多中心放射狀)
- spectral_layout:根據圖的拉普拉斯特征向量排列節
布局也可用pos參數指定,例如,nx.draw(G, pos = spring_layout(G)) 這樣指定了networkx上以中心放射狀分布.

5、按權重划分為重權值得邊和輕權值的邊

elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5]
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5]

6、將Matplotlib圖形保存為全屏圖像

manager = plt.get_current_fig_manager()
manager.window.showMaximized()

7、分圖:

plt.figure(1, figsize=(9, 3))
plt.figure(2, figsize=(9, 3))

8、怎么給plt.subplot加一個主標題?

有suptitle這個函數,專門生成總標題的

plt.figure()
plt.suptitle('Main titile', fontsize=14)
plt.subplot(1, 2, 1)
plt.title('subtitle1')
plt.subplot(1, 2, 2)
plt.title('subtitle2')
plt.show()

9、子圖合並一個圖,不知道數量

lens = len(all_sub_graphs)
b = a = int(math.sqrt(lens))
if a*a < lens:
    b = b+1
plot = plt.subplot(a, b, i+1)

 10、matplotlib去掉坐標軸刻度

 ax.set_axis_off()
 ax.set_xticks([])
 ax.set_yticks([])

 11、label圖例有中文

#coding:utf-8 import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標簽 plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號 #有中文出現的情況,需要u'內容'

12、設置坐標軸

ax = plt.gca()
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)

13、隨機顏色

def random_color():
    color_arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    color = ""
    for i in range(6):
        color += color_arr[random.randint(0, 14)]
    return "#"+color

14、解決linux圖片中文亂碼

plt.rcParams['font.sans-serif'] = ['simhei']  # 用來正常顯示中文標簽

還不行就:

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "D:/Anaconda3/Lib/site-packages/matplotlib\mpl-data/fonts/ttf/simhei.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title(u'中文出來This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This 急急急 the default font', fontproperties=prop)
plt.savefig("chinese.png")

圖例:

plt.legend(loc="best", prop=prop)

15、畫垂直虛線

  • vlines(x, ymin, ymax)
  • hlines(y, xmin, xmax)
plt.vlines(x-values, -5, 100, colors="#808080", linestyles="dashed", label="baseline")

16、圖例位置

plt.legend(handles = [l1, l2,], labels = ['a', 'b'], loc = 'best')

除'best',另外loc屬性有:'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'

17、python中關於圖例legend在圖外的畫法簡析

ax1 = plt.gca()
box = ax1.get_position() 
ax1.set_position([box.x0, box.y0, box.width , box.height* 0.8])
ax1.legend(loc='center left', bbox_to_anchor=(0.2, 1.12),ncol=3)

18、


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM