利用echarts实现有向图可视化

在下方文本框内输入有向图JSON([source, target, value]):

 

上例的源码如下(force-directed-graph.html):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf8"></meta>
<script src="http://cdn.bootcss.com/echarts/3.2.2/echarts.js"></script>
<script src="http://lib.sinaapp.com/js/jquery/1.10.2/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    function draw(){
        var text = $("#graph-input").val();
        var data = eval(text);
        var graph = data2Graph(data);
        drawGraph(graph);
    }

    function data2Graph(data) {
        var graph = {}
        var vertices = {}
        var links = [];
        for (var i = 0; i < data.length; i++) {
            var s = String(data[i][0]);
            var t = String(data[i][1]);
            var v = data[i][2];
            vertices[s] = s;
            vertices[t] = t;
            links.push({'source' : s, 'target' : t, 'value' : v});
        }
        var nodes = [];
        $.each(vertices, function(k, v) {
            nodes.push({'name' : v, 'value' : v});
        });
        graph['links'] = links;
        graph['data'] = nodes;
        return graph;
    }

    function drawGraph(graph) {
        var myChart = echarts.init(document.getElementById("echarts-main"));
        var option = {
            tooltip: {},
            series : [
                {
                    type: 'graph',
                    layout: 'force',
                    symbolSize: 30,
                    edgeSymbol: ['none', 'arrow'],
                    data: graph.data,
                    links: graph.links,
                    roam: true,
                    label: {
                        normal: {
                            show: true,
                            formatter: function (e) {
                                return e['data']['value'];
                            }
                        }
                    },
                    edgeLabel: {
                        normal: {
                            show: true,
                            position: 'middle'
                        }
                    },
                    force: {
                        repulsion: 1000,
                        edgeLength: 200
                    }
                }
            ]
        };
        myChart.setOption(option);
    }

    $(document).ready(function(){
        draw();
        $("#gen-btn").on("click", function(){
            draw();
        });
    });
</script>
</head>
<body>
<p>在下方文本框内输入有向图JSON([source, target, value]):</p>
<textarea id="graph-input" style="height:210px;width:500px">
[[0,1,10], [1,0,1], [1,2,5], [2,0,5]]
</textarea>
<p><button id="gen-btn">生成力导向图</button></p>
<div id="echarts-main" style="height:320px;width:500px;border:1px dashed;"></div>
</body>
</html>

 

本文链接:http://bookshadow.com/weblog/2016/11/22/echarts-directed-graph-visualization/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论