如何在網頁前端裏可視化你的知識圖譜
最近費盡千辛萬苦構造了一份可以用(大概)的知識圖譜,並且把要利用知識圖譜做的領域命名實體識別和一些推薦的功能做成Web版的demo,順帶想實現一些可視化知識圖譜的功能。
(憑啥知識圖譜就只能在Neo4j裏自嗨,不能來前端show一下,歧視嗎(¬_¬))
找了做前端圖表展示的開源庫,D3.js和Echarts都能做,我拿Echarts實現了一下功能,先看一下在現在項目裏一個基於知識圖譜查詢的實際效果:
接下里看看如何的實現:
- 首先在本地下載Echarts相關的js文件,在線引用也可以,html文件裏如下引用:
<script src="/static/js/echarts.common.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
- 給要展示的圖準備一個Dom:
<!-- 爲ECharts準備一個具備大小的Dom -->
<div class = "col-md-12">
<div class="panel panel-default ">
<header class="panel-heading">
關係圖 :
</header>
<div class = "panel-body ">
<div id="graph" style="width: 100%;height:600px;"></div>
</div>
</div>
</div>
3.設置好節點和鏈接關係,這裏爲了簡單手寫了一個蘋果梨子和水果之間的關係,項目裏採用Django框架的交互讀取查詢的結果放入節點(data)和鏈接(links)裏面了:
data = [
{name:'蘋果',category:1,id:0},
{name:'梨子',catagory:1,id:1},
{name:'水果',category:2,id:2}
]
links = [
{source:0,target:2,category:0,value:'屬於',symbolSize:10},
{source:1,target:2,category:0,value:'屬於',symbolSize:10}
]
- 設置Echarts圖:
var myChart = echarts.init(document.getElementById('graph'));
option = {
title: {
text: ''
},
tooltip: {},
animationDurationUpdate: 1500,
animationEasingUpdate: 'quinticInOut',
label: {
normal: {
show: true,
textStyle: {
fontSize: 12
},
}
},
legend: {
x: "center",
show: false
},
series: [
{
type: 'graph',
layout: 'force',
symbolSize: 45,
focusNodeAdjacency: true,
roam: true,
edgeSymbol: ['none', 'arrow'],
categories: [{
name: '查詢實體',
itemStyle: {
normal: {
color: "#009800",
}
}
}, {
name: 'instance',
itemStyle: {
normal: {
color: "#4592FF",
}
}
}, {
name: 'class',
itemStyle: {
normal: {
color: "#C71585",
}
}
}],
label: {
normal: {
show: true,
textStyle: {
fontSize: 12,
},
}
},
force: {
repulsion: 1000
},
edgeSymbolSize: [4, 50],
edgeLabel: {
normal: {
show: true,
textStyle: {
fontSize: 10
},
formatter: "{c}"
}
},
data: data,
links: links,
lineStyle: {
normal: {
opacity: 0.9,
width: 1.3,
curveness: 0,
color:"#262626",
}
}
}
]
};
// 使用剛指定的配置項和數據顯示圖表。
myChart.setOption(option);
這樣就成功實現了一個簡單的圖譜可視化: