在 D3 强制布局节点标签中插入换行符

2024-01-09

因此,我正在使用力定向图,并且我已将鼠标悬停在节点上的 .text 更改为数据中的另一个文本。

我的代码如下所示:

script:

var data = {"nodes":[
                        {"name":"YHO", "full_name":"Yahoo", "type":1, "slug": "www.yahoo.com", "entity":"company", "img_hrefD":"", "img_hrefL":""},
                        {"name":"GGL", "full_name":"Google", "type":2, "slug": "www.google.com", "entity":"company", "img_hrefD":"", "img_hrefL":""},
                        {"name":"BNG", "full_name":"Bing", "type":2, "slug": "www.bing.com", "entity":"company", "img_hrefD":"", "img_hrefL":""},
                        {"name":"YDX", "full_name":"Yandex", "type":2, "slug": "www.yandex.com", "entity":"company", "img_hrefD":"", "img_hrefL":""},

                        {"name":"Desc1", "type":4, "slug": "", "entity":"description"},
                        {"name":"Desc2", "type":4, "slug": "", "entity":"description"},
                        {"name":"Desc4", "type":4, "slug": "", "entity":"description"},

                        {"name":"CEO", "prefix":"Mr.", "fst_name":"Jim", "snd_name":"Bean", "type":3, "slug": "", "entity":"employee"},
                        {"name":"ATT", "prefix":"Ms.", "fst_name":"Jenna", "snd_name":"Jameson", "type":3, "slug": "", "entity":"employee"},
                        {"name":"CTO", "prefix":"Mr.", "fst_name":"Lucky", "snd_name":"Luke", "type":3, "slug": "", "entity":"employee"},
                        {"name":"CDO", "prefix":"Ms.", "fst_name":"Pamela", "snd_name":"Anderson", "type":3, "slug": "", "entity":"employee"},
                        {"name":"CEO", "prefix":"Mr.", "fst_name":"Nacho", "snd_name":"Vidal", "type":3, "slug": "", "entity":"employee"},
                    ], 
            "links":[
                        {"source":0,"target":4,"value":1,"distance":5},
                        {"source":0,"target":5,"value":1,"distance":5},
                        {"source":0,"target":6,"value":1,"distance":5},

                        {"source":1,"target":4,"value":1,"distance":5},
                        {"source":2,"target":5,"value":1,"distance":5},
                        {"source":3,"target":6,"value":1,"distance":5},

                        {"source":7,"target":3,"value":10,"distance":6},
                        {"source":8,"target":3,"value":10,"distance":6},
                        {"source":9,"target":1,"value":10,"distance":6},
                        {"source":10,"target":1,"value":10,"distance":6},
                        {"source":11,"target":2,"value":10,"distance":6},
                        ]
               }    



    var w = 560,
        h = 500,
        radius = d3.scale.log().domain([0, 312000]).range(["10", "50"]);

    var vis = d3.select("body").append("svg:svg")
        .attr("width", w)
        .attr("height", h);

        //vis.append("defs").append("marker")
        //.attr("id", "arrowhead")
        //.attr("refX", 22 + 3) /*must be smarter way to calculate shift*/
        //.attr("refY", 2)
        //.attr("markerWidth", 6)
        //.attr("markerHeight", 4)
        //.attr("orient", "auto")
        //.append("path")
            //.attr("d", "M 0,0 V 4 L6,2 Z"); //this is actual shape for arrowhead

    //d3.json(data, function(json) {
        var force = self.force = d3.layout.force()
            .nodes(data.nodes)
            .links(data.links)
            .linkDistance(function(d) { return (d.distance*10); })
            //.friction(0.5)
            .charge(-250)
            .size([w, h])
            .start();



        var link = vis.selectAll("line.link")
            .data(data.links)
            .enter().append("svg:line")
            .attr("class", function (d) { return "link" + d.value +""; })
            .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; })
            .attr("marker-end", function(d) {
                                                if (d.value == 1) {return "url(#arrowhead)"}
                                                else    { return " " }
                                            ;});


        function openLink() {
            return function(d) {
                var url = "";
                if(d.slug != "") {
                    url = d.slug
                } //else if(d.type == 2) {
                    //url = "clients/" + d.slug
                //} else if(d.type == 3) {
                    //url = "agencies/" + d.slug
                //}
                window.open("//"+url)
            }
        }




        var node = vis.selectAll("g.node")
            .data(data.nodes)
          .enter().append("svg:g")
            .attr("class", "node")
            .call(force.drag);


        node.append("circle")
            .attr("class", function(d){ return "node type"+d.type})
            .attr("r",function(d){if(d.entity == "description"){ return 6 } else { return 18 }})
            //.on("mouseover", expandNode);
            //.style("fill", function(d) { return fill(d.type); })



        node.append("svg:image")
            .attr("class", function(d){ return "circle img_"+d.name })
            .attr("xlink:href", function(d){ return d.img_hrefD})
            .attr("x", "-36px")
            .attr("y", "-36px")
            .attr("width", "70px")
            .attr("height", "70px")
            .on("click", openLink())
            .on("mouseover", function (d) { if(d.entity == "company")
                                                {
                    d3.select(this).attr("width", "90px")
                                    .attr("x", "-46px")
                                    .attr("y", "-36.5px")
                                   .attr("xlink:href", function(d){ return d.img_hrefL});                           
                                                }
                })
            .on("mouseout", function (d) { if(d.entity == "company")
                                            {
                    d3.select(this).attr("width", "70px")
                                    .attr("x", "-36px")
                                    .attr("y", "-36px")
                                   .attr("xlink:href", function(d){ return d.img_hrefD});
                                            }
                });    


        node.append("svg:text")
            .attr("class", function(d){ return "nodetext title_"+d.name })
            .attr("dx", 0)
            .attr("dy", ".35em")
            .style("font-size","10px")
            .attr("text-anchor", "middle")
            .style("fill", "white")
            .text(function(d) { if (d.entity != "description"){return d.name} });


        node.on("mouseover", function (d) {
            if (d.entity == "company"){   
                d3.select(this).select('text')
                    .transition()
                    .duration(300)
                    .text(function(d){
                            return d.full_name;
                        })
                    .style("font-size","15px")

            }
            else if(d.entity == "employee"){
                d3.select(this).select('text')
                    .transition()
                    .duration(300)
                    .text(function(d){return d.prefix + ' ' + d.fst_name + ' ' + d.snd_name})
                    .style("font-size","8px")   

            }
            else {
                d3.select(this).select('text')
                    .transition()
                    .duration(300)
                    .style("font-size","15px")
            }

            if (d.entity == "company") {
                d3.select(this).select('image')
                    .attr("width", "90px")
                    .attr("x", "-46px")
                    .attr("y", "-36.5px")
                    .attr("xlink:href", function (d) {
                        return d.img_hrefL
                        });               
            }

            if (d.entity == "company") {

                d3.select(this).select('circle')
                                .transition()
                                .duration(300)
                                .attr("r",28)

            }
            else if (d.entity == "employee"){
                d3.select(this).select('circle')
                                .transition()
                                .duration(300)
                                .attr("r",32)
            }
        })


         node.on("mouseout", function (d) {
            if (d.entity == "company") {
                d3.select(this).select('text')
                    .transition()
                    .duration(300)
                    .text(function(d){return d.name;})
                    .style("font-size","10px")
                }
            else if(d.entity == "employee"){
                d3.select(this).select('text')
                    .transition()
                    .duration(300)
                    .text(function(d){return d.name;})
                    .style("font-size","10px")  

            }
            else {
                d3.select(this).select('text')
                    .transition()
                    .duration(300)
                    .style("font-size","10px")
            }


             if (d.entity == "company") {
                d3.select(this).select('image')
                    .attr("width", "70px")
                    .attr("x", "-36px")
                    .attr("y", "-36px")
                    .attr("xlink:href", function (d) {
                    return d.img_hrefD
                });
            }

            if (d.entity == "company" || d.entity == "employee") {

                d3.select(this).select('circle')
                                .transition()
                                .duration(300)
                                .attr("r",18)
            }

        });

        force.on("tick", function() {
          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; });

          node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
        });
    //});

你可以在我的 jsfiddle 中看到工作示例:http://jsfiddle.net/dzorz/6pHkn/ http://jsfiddle.net/dzorz/6pHkn/

令我困扰的代码部分是鼠标悬停:

else if(d.entity == "employee"){

     d3.select(this).select('text')
                .transition()
        .duration(300)
        .text(function(d){return d.prefix + ' ' + d.fst_name + ' ' + d.snd_name})
        .style("font-size","8px")   

}

我想在之间添加换行符d.fst_name and d.snd_name我尝试过'\n' and '<\br>'它没有做我想做的事......

d3中在文本上添加换行符的方法是什么?

您可以编辑上面链接的 jsfiddle...

任何建议都欢迎


这是在 SVG 中不使用 HTML 的答案,因为由于某种原因它不能与这种强制的东西一起工作。

else if(d.entity == "employee"){
                var asdf = d3.select(this);
                asdf.select('text').remove();

                asdf.append("text")
                            .text(function(d){return d.prefix + ' ' + d.fst_name })
                            .attr("class","nodetext")
                            .attr("dx", 0)
                            .attr("dy", ".35em")
                            .style("font-size","5px")
                            .attr("text-anchor", "middle")
                            .style("fill", "white")
                            .transition()
                            .duration(300)
                            .style("font-size","12px");

                asdf.append("text").text(function(d){return d.snd_name })
                            .attr("class","nodetext")
                            .attr("transform","translate(0, 12)")
                            .attr("dx", 0)
                            .attr("dy", ".35em")
                            .style("font-size","5px")
                            .attr("text-anchor", "middle")
                            .style("fill", "white")
                            .transition()
                            .duration(300)
                            .style("font-size","12px");                                         
            }

Jsfiddle 示例:http://jsfiddle.net/cuckovic/FWKt5/ http://jsfiddle.net/cuckovic/FWKt5/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 D3 强制布局节点标签中插入换行符 的相关文章

  • 更改 的默认按钮标签

    我在用
  • d3 地理投影从正交到 X 的过渡

    我正在开发一个教育地图项目 其中显示不同的地图投影 我想在选择不同投影之间实现变形过渡 我找到了一个很好的例子来实现它 并且我没有遇到太多的麻烦来重新创建它 不幸的是 我还需要裁剪投影的功能 这与目标状态完美配合 但在改变投影时则不然 当选
  • D3.js 中的点图

    我有兴趣创建一个Dot plot 每个数据值都有连续的点 但到目前为止我所管理的是为每个值创建一个点 更清楚地说 假设对于 array1 我希望第一个值创建 5 个圆圈 第二个值创建 4 个圆圈 依此类推 array1 5 4 2 0 3
  • d3 同步 2 个独立的缩放行为

    我有以下 d3 d3fc 图表 https codepen io parliament718 pen BaNQPXx https codepen io parliament718 pen BaNQPXx 该图表的主要区域有缩放行为 y 轴有
  • D3:如何在Groups of Force布局节点上绘制多个凸包?

    我试图在力布局中的所有组上绘制凸包 但我只画出了一半的凸包 当 D3 尝试绘制其余的船体时 控制台返回错误 元素尚未创建 然而 当我检查控制台中的 groups 变量时 所有组数据都在那里 x y 数据都设置得很好 见下图 我什至尝试在ti
  • 在 d3 中应用转换时出现错误

    我正在尝试对我在 d3 中设计的条形图应用一些过渡效果 这是我的代码 svg selectAll bar data data enter append g attr class bar append rect attr rx barRadi
  • d3力定向布局-链接距离优先

    在 d3 中使用力导向布局 如何使链接距离成为优先事项 同时仍然保持良好的图形布局 如果我指定动态链接距离 但保留默认费用 则我的图形距离会因费用函数而发生一些变形 并且不再是准确的距离 但是 如果我删除电荷 图表将如下所示 任何建议表示赞
  • 使圆圈与 d3.js 上的多线匹配相同的颜色过滤?

    我有一个多线图 当按每种水果过滤时会更新 每条线条颜色对应不同的销售年份 在 的帮助下Shashank https stackoverflow com users 5569282 shashank 每个数据点线上的圆圈已添加到组中 而不是直
  • 在 Crossfilter 中使用过滤器

    我刚刚开始使用 crossfilter 和 d3 js 我正在尝试 API 参考中给出的一些片段 我有以下数据 var payments crossfilter date 2011 11 14T16 17 54Z quantity 2 to
  • 如何在 d3 js 中突出显示从根到选定节点的路径?

    我使用 d3 js 创建了一棵树 现在我创建了一个下拉菜单 其中包含树中所有节点的列表 现在 从下拉菜单中选择一个节点时 我想突出显示从根到该特定节点的路径 这个怎么做 首先创建一个 flatten 函数 它将分层数据变成一个 n 数组 f
  • 需要js、d3 和 nvd3 集成

    我面临整合的问题要求 questions tagged requirejs with d3 questions tagged d3 and nvd3 questions tagged nvd3 我找到了一个使用 require 的简单解决方
  • 增加 D3 图中边缘的可点击区域

    我有一个由 d3 制作的图 dagre d3 位于其顶部用于绘制有向图 这给出了我对渲染图表的期望 要编辑构建图表的数据 每个元素都是可单击的 这对于使用标签渲染边缘的情况来说很好 但它们并不总是有标签 导致未标记的边缘很难单击进行编辑 分
  • d3 仅限整数刻度线

    我有一个 d3 条形图 其值范围为 0 3 我希望 y 轴仅显示整数值 我可以这样做 var yAxis d3 svg axis scale y orient right tickFormat d3 format d 但是 非整数标记处仍然
  • 如何在“object”标签内选择 SVG?

    HTML 页面的内容如下所示 方法如下script js looks var tooltip d3 select body append div style position absolute sty
  • 为什么我的 D3 SVG 图上的轴不会更新?

    I have 简单的 D3 散点图 http www raxacoricofallapatorius com test scattertest html我在显示数据的几个不同属性之间切换 但是虽然我可以更改数据点 并按照我想要的方式进行转换
  • 如何在 Angular 2 中实现 D3

    我想将这段代码从 d3 js 实现到 Angular 2 组件 但我不知道如何将 js 文件调用到组件 ts 文件中 我找到了一些折线图的代码 包括index html和lineChart js 我怎样才能调用javascriptngAft
  • d3 v4 使用 TypeScript 进行拖放

    我正在使用 D3 库 v4 和 Angular2 我想拖放 svg 元素 我有一个代码 item call d3 drag on start dragStarted on drag dragged on end dragEnded and
  • MATLAB 子图标题和轴标签

    我有以下脚本来最终绘制 4 x 2 子图 files getAllFiles preliminaries n size files cases cell 1 n m cell 1 n for i 1 1 n S load files i c
  • dc js 复合条形图 折线图

    我有一个 dc js 条形图 如下所示这个叉形小提琴 http jsfiddle net 89218vf1 3 此条形图将加载预定义的过滤器 例如本例中的 25 35 现在 我需要显示一个与条形图复合的折线图 突出显示带有高低线的过滤数据
  • 获取现有 SVG 元素的属性并使用 d3.js 绑定为数据

    我有一个现有的 svg 元素 例如

随机推荐

  • 更改ckeditor的背景?

    如何更改用户键入文本的 CKEditor 的背景颜色 我需要动态地执行此操作 但找不到需要更改的元素 知道如何瞄准它吗 您可以尝试 CKEDITOR instances editor1 document getBody setStyle b
  • 检查密码是否包含字母数字和特殊字符

    如何检查字符串passwordText是否至少包含 1 个字母字符 1 号 1 个特殊字符 符号 尝试这个 bool result passwordText Any c gt char IsLetter c passwordText Any
  • Android 中的无效区域是什么?

    在 Android如何绘制视图 主题下 有这样一句话 绘图从根节点开始 布局 要求测量 并绘制布局树 绘图是 通过走树来处理 渲染每个相交的视图 这无效区域 而且我不太理解 无效区域 这个词 这里是引文的来源文章 http develope
  • Jquery Mobile 弹出菜单不起作用

    我正在尝试构建一个虚拟页面来理解 Jquerymobile 但我无法实现 菜单 单击页面上的菜单按钮 处理以下链接 http jquerymobile com branches popup widget docs pages popup i
  • 使用 gson 错误转换 json 预期为 BEGIN_OBJECT,但在第 1 行第 2 列路径 $ 处为 BEGIN_ARRAY

    user id 5633795 username Vorago count300 203483 count100 16021 count50 1517 playcount 1634 ranked score 179618425 total
  • 从字符串中删除换行符

    我有一个像这样的字符串 var aString This is a string n n This is the second line of the string n n 文本视图内部如下所示 This is a string This
  • async wait 与 TcpClient 的使用

    我最近开始使用新的 C 5 0 async 和 await 关键字 我以为我得到了转折 但意识到一件事让我怀疑 以下是我如何从远程 TcpClient 异步接收数据 一旦我接受连接 我就调用这个函数 static async void Re
  • 如何在查询字符串中包含特殊字符?

    URL http localhost mysite mypage param 123工作正常 但是 如果我想在其中添加一些特殊字符param like 那么 URL 就变成了http localhost mysite mypage para
  • Flutter 中的设备国家/地区

    我正在尝试在 Flutter 中获取设备国家 地区 Android 我用了本教程 https flutter dev docs development accessibility and localization international
  • 尝试在 Cloud Run 中使用 Google Cloud Storage 时调用者没有权限

    我正在尝试使用 Cloud Storage 在 Google Cloud Run 上设置 Node 项目 使用创建的服务帐户时 我遇到了身份验证问题 创建服务帐户时 我成功下载了 JSON 令牌 并使所有内容在本地开发环境中正常运行 问题是
  • 为什么 Rails 的“HashWithIn DifferentAccess”将键存储为字符串而不是符号?

    我在用enum将数据库中的整数映射到 ruby 代码中的语义值 但是我注意到它使用的键是字符串 当我检查哈希的类型时 我发现它是一个ActiveSupport HashWithIndifferentAccess 不是一个标准Hash 这是有
  • django 和 mod_wsgi 的配置问题

    我在让 django 使用 mod wsgi 在 apache 2 2 上工作时遇到问题 Django 和 mod wsgi 都已安装 我什至可以在访问路径时看到 404 页面 并且可以登录 django admin 但如果我想安装标记模块
  • 合并hdfs文件

    我在 HDFS 中有 1000 多个可用文件 命名约定为1 fileName txt to N fileName txt 每个文件的大小为 1024 MB 我需要将这些文件合并到一个 HDFS 中 并保持文件的顺序 说5 FileName
  • 在elasticsearch中计算地理距离

    我正在使用geo distance filter http www elasticsearch org guide reference query dsl geo distance filter html with tire https g
  • Autofac 和 ASP.NET Web API ApiController

    我已经在 MVC 3 中使用 autofac 一段时间了 并且很喜欢它 我最近将一个项目升级到 MVC 4 除了 Web Api ApiController 之外 一切似乎都正常工作 我收到以下异常 An error occurred wh
  • 根据 pom 中的活动配置文件更改包装

    我有一个用 Maven 编译的项目 我在 pom xml 中声明了不同的配置文件 对于其中一些配置文件 我更喜欢构建战争 而对于其他配置文件 我更喜欢罐子 我用来手动编辑 pom xml 文件并将打包变量更改为
  • iOS:Testflight 没有可供外部测试人员使用的版本

    我正在使用 testflight 作为我的应用程序的 Beta 测试工具 我已上传构建 但邀请已成功发送给内部测试人员 但没有邀请发送给外部测试人员 Below image shows both the groups has been in
  • 未捕获的引用错误:__importDefault 未定义

    我是角度新手 我在我的中遇到这个错误index component ts file 未捕获的引用错误 importDefault 未定义 附上错误截图 https i stack imgur com xUKWA png 我从 8 升级到 9
  • React Native - 具有动态高度子项的 FlatList

    我一直在努力将类似砖石的风格融入我的应用程序中 我尝试应用react native masonry包裹 但是您必须传递图像网址 我正在尝试实现相同的样式 但渲染文本而不一定渲染图像 到目前为止 我已经解决了FlatList 但这是我所能得到
  • 在 D3 强制布局节点标签中插入换行符

    因此 我正在使用力定向图 并且我已将鼠标悬停在节点上的 text 更改为数据中的另一个文本 我的代码如下所示 script var data nodes name YHO full name Yahoo type 1 slug www ya