Bokeh|互動式資料視覺化庫Bokeh製作網路圖

Bokeh增加了對建立網路圖視覺化的原生支援,並可在邊和節點之間進行可配置的互動。今天呢,我們直接從示例入手,講解每句程式碼的含義。

先看一下效果圖:

Bokeh|互動式資料視覺化庫Bokeh製作網路圖

#匯入需要的python包和函式

import math

from bokeh。io import show, output_file

from bokeh。plotting import figure

from bokeh。models import GraphRenderer, StaticLayoutProvider, Oval

from bokeh。palettes import Spectral8

N = 8 #網路圖的節點數

node_indices = list(range(N)) #生成0到N-1的列表,即[0, 1, 2, 3, 4, 5, 6, 7]

plot = figure(width=900, height=500, title=‘Graph Layout Demonstration’, x_range=(-1。1,1。1), y_range=(-1。1,1。1))

#定義圖片寬、高的大小,標題,x軸、y軸的範圍

graph = GraphRenderer() #GraphRenderer()函式用來渲染網路圖的節點和邊

graph。node_renderer。data_source。add(node_indices, ‘index’)

graph。node_renderer。data_source。add(Spectral8, ‘color’)

graph。node_renderer。glyph = Oval(height=0。1, width=0。1, fill_color=‘color’) #定義節點的大小,顏色

graph。edge_renderer。data_source。data = dict(start=[0]*N, end=node_indices) #定義網路圖邊線的起始資料來源

# 開始佈局程式碼

circ = [i*2*math。pi/8 for i in node_indices]

x = [math。cos(i) for i in circ]

y = [math。sin(i) for i in circ]

graph_layout = dict(zip(node_indices, zip(x, y)))

graph。layout_provider = StaticLayoutProvider(graph_layout=graph_layout)

plot。renderers。append(graph)

#匯出html檔案

output_file(‘graph。html’)

#展示結果

show(plot)