在 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 响应式:viewBox 与 resize()?

    我必须构建在平板电脑 桌面显示器以及某些情况下非常大的 4k 高分辨率影院尺寸显示器上都能正常运行的 d3 可视化效果 因此 我试图找出使用 SVG 的 viewBox 属性和 preserveaspectratio 与调用调整大小函数以在
  • AbsoluteLayout - 测量标签高度而不将标签放置在 UI 上

    我在 AbsoluteLayout 中手动定位标签 为了正确地做到这一点 我想在将标签放置在用户界面上之前知道标签的高度 我找到了这个解决方案 但并非没有实际放置标签 public double MeasureLabelHeight str
  • 如何从此 d3.js layout.tree 获取树祖先和树后代的列表?

    我正在尝试和修改this https bl ocks org mbostock 4339083d3 js 的示例 用于根据 JSON 树结构绘制树 这就是树的一部分开始时的样子 我正在尝试进行两个单独的修改 但我不知道该怎么做 当单击节点的
  • 将文本添加到 ggplot 中的轴标签

    我从下表中绘制了一个图表 BoatPhs fit se lower upper 1 Before 3 685875 0 3287521 3 038621 4 333130 2 After0 20NTA 3 317189 0 6254079
  • 合并两个 csv (d3)

    我使用以下代码加载两个 csv 文件 d3 csv sqrt100train csv function error data2 d3 csv sqrt100test csv function error data sqrt100train
  • 当通过 javascript 填充输入框时,使物化标签移出输入框

    通常情况下 与物化 http materializecss com 文本输入框的标签显示在输入框中 直到用户选择该框并在其中输入文本 但是 当通过 javascript 填充框的值时 标签不会移开 它保留在框中并与输入的文本重叠 有没有办法
  • 在 d3.js 中换行长文本

    我想将长文本元素换行为宽度 这里的例子取自博斯托克的wrap功能 http bl ocks org mbostock 7555321 但似乎有两个问题 首先 wrap的结果没有继承元素的x值 文本左移 其次它绕在同一条线上 并且lineHe
  • 快速响应的交互式图表/图形:SVG、Canvas 还是其他?

    我正在尝试选择正确的技术来更新一个项目 该项目基本上在可缩放 可平移的图表中渲染数千个点 当前使用 Protovis 的实现性能不佳 在这里查看 http www planethunters org classify http www pl
  • D3 时间解析返回 null

    根据此页面上的说明 https github com mbostock d3 wiki Time Formatting https github com mbostock d3 wiki Time Formatting我正在尝试解析 ISO
  • 多个链接 dc.js 图表的 d3-tooltips

    我正在寻找修改 dc js 的开箱即用工具提示 似乎有一个解决方案使用d3 js 工具提示 https github com Caged d3 tip as in 这个问题 https stackoverflow com questions
  • D3 删除千位的逗号分隔符

    我有一个包含 3 列的 json 其中一列是 年份 该列仅包含年份 没有日期 当我在 x 轴上绘制它时 年份会以逗号分隔符表示数千 所以在 json 中 日期的格式是 Year 1990 在 x 轴上 结果是 1 990 我一直在试图弄清楚
  • 如何在D3节点中放置图像?

    到目前为止 我已经创建了这些 D3 节点 用于创建可折叠的层次树 到目前为止 这些节点的颜色为 AA1C1C 深红色 以表明如果您单击它们 它们将扩展到更多节点 我想要做的是在节点中使用图像中的位置 这对于所有用户来说都是一个加号 以知道它
  • 调整发散堆积条形图以使用通用更新模式

    我一直在使用可用的堆积条形图示例here https bl ocks org mbostock b5935342c6d21928111928401e2c8608使用以下代码 var data month Q1 2016 apples 384
  • 强制 GtkLabel 剪裁其居中对齐的文本

    我有一个GtkLabel其文本无论比标签短还是长都保持居中 例如 Win32 静态控件具有SS CENTER样式标志集的行为如下 Lorem ipsum dolor 当文本短于控件时 Lorem ipsum dolor sit amet c
  • D3.js 从 file:/// 加载本地数据文件

    我知道D3 js支持使用XHR和JSONP加载数据文件requests https github com mbostock d3 wiki Requests 但就我而言 我将通过从文件系统双击 html 文件来运行它们 这将像file fo
  • 如何让d3.js生成svg而不绘制它?

    有没有办法只生成 svg 并将其作为字符串获取 而不实际绘制它 我考虑过将 svg 渲染到隐藏的 div 然后读取内部 html 但是有没有更干净的方法 我认为你可以这样做 var svg d3 select body append svg
  • 使用 Meteor 中的 D3 访问 csv 文件

    我已经使用 D3 成功渲染了一个 HTML 表格 显示了 csv 文件中的数据 但是当我将相同的代码移入 Meteor 项目时 我遇到了问题 传递到 d3 csv 回调中的数据对象一次拾取 HTML 文件 1 行 而不是 csv 数据 仅当
  • 窗口调整大小事件上的响应式画布

    我是画布概念的新手 我正在尝试使用 D3 js 绘制画布 我想让画布根据窗口屏幕大小进行响应 function onResize var element document getElementsByTagName canvas 0 var
  • 中断并标签,“标签 MyLabel 丢失”

    我有这样的代码 if condition1 break MyLabel while true some code here MyLabel if condition2 break more code here 我收到此错误 标签 MyLab
  • crossfilter - 计算具有属性的所有记录的百分比

    这是我的问题 我正在使用 python Flask 服务器从 mongo db 获取 json 数据 并在其中指定要导入的字段 此数据采用 json 格式 并且仅像这样获取 一旦通过 graphs js 中的 crossfilter 是否可

随机推荐

  • 更改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