如何在网页前端里可视化你的知识图谱
最近费尽千辛万苦构造了一份可以用(大概)的知识图谱,并且把要利用知识图谱做的领域命名实体识别和一些推荐的功能做成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);
这样就成功实现了一个简单的图谱可视化: