d3知识图谱的绘制

  1. 先在html文件中准备一个定义了高宽的 DOM 容器
    <div id="graph" style="width: 100%;height:900px;"></div>
    
  2. 引入js
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="https://d3js.org/d3.v3.min.js" type="text/javascript"></script>
    
  3. 开始写js代码
    	getAllDate(company_name, deep);
    
        // 查询全部数据
    function getAllDate(company_name, deep) {
        //console.log(company_name);
        //console.log(deep);
        var svg_elem = $("#graph").find("svg");
        svg_elem.remove();
        $.ajax({
            type: "GET",
            url: "{% url 'znfk:demograph:demo_graph_data' %}",
            dataType: 'json',
            data: {'company_name': company_name, 'deep': deep},
            success: function (data) {
                get_svg(data, company_name)
            },
            error: function () {
                console.log('error')
            }
        })
    }
    
        // 得到数据,绘制svg图形
    function get_svg(graph, company_name) {
    
        var width = $("#graph").width(),
            height = $("#graph").height();
    
        var force = d3
            .layout  // layout将json格式转化为力学图可用的格式
            .force() // 构造力导向布局
            //.forceSimulation().force("center",d3.forceCenter(width/2,height/2))
            .charge(-200)
            .size([width, height]) //作用域的大小
            //.linkDistance(50) //连接线长度
            .linkDistance(150) //连接线长度
            .charge(-2000)//顶点的电荷数。该参数决定是排斥还是吸引,数值越小越互相排斥
    		//.gravity(0.05);
    
        var svg = d3.select("#graph")
            .append("svg")
            .attr("width", width)
            .attr("height", height)
            .attr("pointer-events", "all")
    
        var r = 32;
    
        //箭头
        var marker =
            svg.append("marker")
            //.attr("id", function(d) { return d; })
                .attr("id", "resolved")
                //.attr("markerUnits","strokeWidth")//设置为strokeWidth箭头会随着线的粗细发生变化
                .attr("markerUnits", "userSpaceOnUse")
                .attr("viewBox", "0 -5 10 10")//坐标系的区域
                .attr("refX", r + 10)//箭头坐标  X
                .attr("refY", 0)//箭头坐标  Y
                .attr("markerWidth", 15)//标识的大小  箭头宽度
                .attr("markerHeight", 10)//  箭头高度
                .attr("orient", "auto")//绘制方向,可设定为:auto(自动确认方向)和 角度值  箭头的方向为自动适应线条的方向
                .attr("stroke-width", 2)//箭头宽度
                .append("path")
                .attr("d", "M0,-5L10,0L0,5")//箭头的路径
                .attr('fill', 'gray');//箭头颜色
                //.attr('fill','#CCCDCF');//箭头颜色
    
        var zoom = d3.behavior.zoom()
            .scaleExtent([1 / 10, 5]) // scaleExtent 用于设置最小和最大的缩放比例
            .on("zoom", zoomed); // 当 zoom 事件发生时,调用 zoomed 函数
    
        force
            .nodes(graph.all_data.nodes)
            .links(graph.all_data.links)
            .start(); //  启动模拟
    
        //console.log(graph.all_data.nodes);
        //console.log(graph.all_data.links);
    
        svg.call(zoom)
            .on("dblclick.zoom", null);  // 取消双击放大的问题
            //.on('mousemove',mouseMove);
    
        var link = svg.append("g")
            .selectAll(".link")
            .data(graph.all_data.links)
            .enter()
            .append("line")
            .attr("id", function (d) {
                return d.id
            })
            //.attr("class", "link")
            //.style("stroke-width", 1)//线条粗细
            //.style("fill", '#666')//线条粗细
            .attr("marker-end", "url(#resolved)");//根据箭头标记的id号 标记箭头
    
        var linksText = svg.append("g")
            .selectAll(".text")
            .data(graph.all_data.links)
            .enter()
            .append("text")
            .attr("class", function (d) {
                return d.id
            })
            .text(function (d) {
                return d.prop;
            });
    
        //console.log(graph.nodes)
        var node = svg.append("g")
            .selectAll(".node")
            .data(graph.all_data.nodes)
            .enter()
            .append("circle")
            .attr("id", function (d) {
                return d.CID
            })
            .attr("class",function (node, i) {
                if(node.color=='2'){
                    return 'company'
                }
            })
            .style("fill", function (node, i) {
                if (node.name == company_name) {
                    return color = '#C03939'
                }
                else if (node.color == '2') { //p2p
                    return color = "#1943AC";
                }
                else {
                    //return color = "#5095FF";
                    return color = "#cea539";
                }
            })
            .attr("r", r)
            .style('stroke', '#fff')
            //.call(force.drag) ;//将当前选中的元素传到drag函数中,使顶点可以被拖动
            .call(force.drag().on("dragstart", function (d, i) {
                d.fixed = true;    //拖拽开始后设定被拖拽对象为固定
                d3.event.sourceEvent.stopPropagation(); //避免了当拉拽网络节点时也拽动整个图形。
            }));
    
    
        //var text_dx = 10;
        //var text_dy = 25;
        //添加描述节点的文字
        var nodes_text = svg.append("g").selectAll(".nodetext")
            .data(graph.all_data.nodes)
            .enter()
            .append("text")
            .attr("dy", ".35em")
            .attr("text-anchor", "middle")
            .style("fill", "#FFF")
            //.style("font", "12px Microsoft YaHei bold")
            //.style("font-size", 12)
            .attr('x', changeline);
    
        //定义圈内文字分行
        function changeline(d) {
            var re_en = /[a-zA-Z]+/g;
            // 英文
            if (d.name.match(re_en)) {
                if (d.name.length <= 6) {
                    d3.select(this).append('tspan')
                        .text(function () {
                            return d.name;
                        });
                }
                else if (d.name.length > 6 && d.name.length <= 12) {//大于4  这两行
                    var top = d.name.substring(0, 6);
                    var bot = d.name.substring(6, d.name.length);
    
                    d3.select(this).append('tspan')
                        .attr('dx', -11)
                        .attr('dy', -7)
                        .text(function () {
                            return top;
                        });
    
                    d3.select(this).append('tspan')
                        .attr('dx', -50)
                        .attr('dy', 20)
                        .text(function () {
                            return bot;
                        });
    
    
                }
                else if (d.name.length > 12 && d.name.length <= 18) {// 文字长度大于8 折三行
                    var top = d.name.substring(0, 6);
                    var bot = d.name.substring(6, 12);
                    var bot1 = d.name.substring(12, 18);
    
                    d3.select(this).append('tspan')
                        .attr('dx', 0)
                        .attr('dy', -9)
                        .text(function () {
                            return top;
                        });
    
                    d3.select(this).append('tspan')
                        .attr('dx', -40)
                        .attr('dy', 15)
                        .text(function () {
                            return bot;
                        });
    
                    d3.select(this).append('tspan')
                        .attr('dx', -40)
                        .attr('dy', 15)
                        .text(function () {
                            return bot1;
                        });
                }
                else if (d.name.length > 18) {// 文字长度大于8 折三行
                    var top = d.name.substring(0, 6);
                    var bot = d.name.substring(6, 12);
                    var bot1 = d.name.substring(12, 18) + '...';
    
                    d3.select(this).append('tspan')
                        .attr('dx', 3)
                        .attr('dy', -9)
                        .text(function () {
                            return top;
                        });
    
                    d3.select(this).append('tspan')
                        .attr('dx', -44)
                        .attr('dy', 15)
                        .text(function () {
                            return bot;
                        });
    
                    d3.select(this).append('tspan')
                        .attr('dx', -42)
                        .attr('dy', 15)
                        .text(function () {
                            return bot1;
                        });
                }
            }
            else {
                // 中文
                if (d.name.length <= 4) {
                    d3.select(this).append('tspan')
                        .text(function () {
                            return d.name;
                        });
                }
                else if (d.name.length > 4 && d.name.length <= 8) {
                    var top = d.name.substring(0, 4);
                    var bot = d.name.substring(4, d.name.length);
    
                    d3.select(this).append('tspan')
                        .attr('dx', -2)
                        .attr('dy', -7)
                        .text(function () {
                            return top;
                        });
                    d3.select(this).append('tspan')
                        .attr('dx', -47)
                        .attr('dy', 22)
                        .text(function () {
                            return bot;
                        });
    
                }
                else if (d.name.length > 8 && d.name.length <= 10) {
                    var top = d.name.substring(0, 4);
                    var mid = d.name.substring(4, 8);
                    var bot = d.name.substring(8, d.name.length);
    
                    d3.select(this).append('tspan')
                        .attr('dx', -7)
                        .attr('dy', -9)
                        .text(function () {
                            return top;
                        });
                    d3.select(this).append('tspan')
                        .attr('dx', -50)
                        .attr('dy', 17)
                        .text(function () {
                            return mid;
                        });
                    d3.select(this).append('tspan')
                        .attr('dx', -40)
                        .attr('dy', 17)
                        .text(function () {
                            return bot;
                        });
    
                }
                else if (d.name.length > 10) {
                    var top = d.name.substring(0, 4);
                    var mid = d.name.substring(4, 8);
                    var bot2 = d.name.substring(8, 10);
                    bot2 += '...'
    
                    d3.select(this).append('tspan')
                        .attr('dx', -5)
                        .attr('dy', -9)
                        .text(function () {
                            return top;
                        });
                    d3.select(this).append('tspan')
                        .attr('dx', -50)
                        .attr('dy', 17)
                        .text(function () {
                            return mid;
                        });
                    d3.select(this).append('tspan')
                        .attr('dx', -40)
                        .attr('dy', 17)
                        .text(function () {
                            return bot2;
                        });
    
                }
            }
        }
    
    
        // 提示框
        node.append("title")
            .text(function (d) {
                if (d.score) {
                    if (d.score != 0) {
                        return d.name + "  综合得分:" + d.score + "  综合等级:" + d.rank;
                    } else {
                        return d.name
                    }
                } else {
                    return d.name
                }
            });
    
    
        function zoomed() {
            svg.selectAll("g").attr("transform",//svg下的g标签移动大小
                "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
        }
    
        // force feed algo ticks
        // 触发仿真第一步(如更新节点的x和y属性)
        force.on("tick", function () {  // 对于每一个时间间隔
            // alpha 参数。这个值最开始是 1,随着图形趋于稳定,它也会逐渐趋近 0
            // if(force.alpha()<=0.05) {  // 足够稳定时,才渲染一次
            // 更新连线坐标
            link.attr("x1", function (d) {
                return d.source.x;
            })
                .attr("y1", function (d) {
                    return d.source.y;
                })
                .attr("x2", function (d) {
                    return d.target.x;
                })
                .attr("y2", function (d) {
                    return d.target.y;
                });
    
            // 更新文字坐标
            linksText
                .attr("x", function (d) {
                    return (d.source.x + d.target.x) / 2;
                })
                .attr("y", function (d) {
                    return (d.source.y + d.target.y) / 2;
                });
    
            node.attr("cx", function (d) {
                return d.x;
            })
                .attr("cy", function (d) {
                    return d.y;
                });
            nodes_text.attr("x", function (d) {
                return d.x;
            })
                .attr("y", function (d) {
                    return d.y;
                });
        });
    }
    
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值