D3 js图中相同颜色的箭头和链接

2024-01-08

我是 D3 的新手,一直在尝试使箭头的颜色与 D3 图中箭头的颜色相同,参考给出的代码解决方案here https://stackoverflow.com/questions/32964457/match-arrowhead-color-to-line-color-in-d3.

它是一个有向图,json 文件负责链接各个节点。我试图确保无论我的链接是什么颜色,我的箭头都会获得相同的颜色,但这似乎不起作用。这是我的js代码:

var width = 960,
height = 500;

// initialization
var svg = d3.select("div").append("svg")
    .attr("width", width)
    .attr("height", height);

var force = d3.layout.force()
    .gravity(0) // atom's cohesiveness / elasticity of imgs :)
    .distance(150) // how far the lines ---> arrows :)
    .charge(-50) // meta state transition excitement
    .linkDistance(140)
    //.friction(0.55) // similar to charge for quick reset :)
    .size([width, height]); // degree of freedom to the canvas

// exception handling
d3.json("/assets/javascripts/position.json", function(error, json) {
     if (error) throw error;
          // Restart the force layout
    force
      .nodes(json.nodes)
      .links(json.links)
      .start();

      var pipeline = document.getElementById("pipeline").innerHTML;

      // Build the link
      var link = svg.selectAll(".links")
      .data(json.links)
      .enter().append("line")
      .attr("class", "lol")
      .style("stroke-width", "2")
      .attr("stroke", function(d){
        return linkColor(d.colorCode);})
      .each(function(d) {
        var color = linkColor(d.colorCode);
        d3.select(this).attr("marker-end", marker(color));
      });

      function marker(color) {
        svg.append("svg:marker")
          .attr("id", color.replace("#", ""))
          .attr("viewBox", "0 -5 10 10")
          .attr("refX", 15)
          .attr("refY", 0)
          .attr("markerWidth", 9)
          .attr("markerHeight", 9)
          .attr("orient", "auto")
          .attr("markerUnits", "userSpaceOnUse")
          .append("svg:path")
          .attr("d", "M0,-5L10,0L0,5")
          .style("fill", linkColor(color));

        return "url(" + linkColor(color) + ")";
      };
      var node = svg.selectAll(".nodes")
      .data(json.nodes)
      .enter().append("g")
      .attr("class", "node")
      .call(force.drag);

      node.append("svg:image")
                  .attr("xlink:href", "") // update the node with the image
                  .attr("x", function(d) { return -5;}) // how far is the image from the link??
                  .attr("y", function(d) { return -25;}) // --- same ---
                  .attr("height", 55) // size
                  .attr("width", 55);

      // Define the div for the tooltip
      var div = d3.select("body").append("pre")
      .attr("class", "tooltip")
      .style("opacity", 0);

      node.append("text")
        .attr("class", "labelText")
        .attr("x", function(d) { return -5;})
        .attr("y", function(d) { return 48;})
        .text(function(d) { return d.label });

      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 + ")"; });

        force.stop();
      });

      function linkColor(linkCode) {
        switch (linkCode)
        {
          case 'ctoc':
            return '#0000FF';//blue
            break;
          case 'ctof':
            return '#00afaa';//green
            break;
          case 'ftoc':
            return '#fab800';//yellow
            break;
          case 'ftof':
            return '#7F007F';//purple
            break;
          default:
            return '#0950D0';//generic blue
            break;
        }
      }
});

其中position.json是:

    {
  "nodes": [
    {"x": 100, "y": 100},
    {"x": 250, "y": 100},
    {"x": 400, "y": 100},
    {"x": 550, "y": 200},
    {"x": 700, "y": 200},
    {"x": 100, "y": 300},
    {"x": 250, "y": 300},
    {"x": 400, "y": 300}
  ],
  "links": [
    {"source":  0, "target":  1, "colorCode" : "ctof"},
    {"source":  1, "target":  2, "colorCode" : "ftoc"},
    {"source":  2, "target":  3, "colorCode" : "ctof"},
    {"source":  3, "target":  4, "colorCode" : "ftoc"},
    {"source":  5, "target":  6, "colorCode" : "ctof"},
    {"source":  6, "target":  7, "colorCode" : "ftoc"},
    {"source":  7, "target":  3, "colorCode" : "ctof"}
  ]
}

但我在屏幕上看不到任何输出。有人可以帮我确定我哪里出了问题吗?


微小的变化:

In the marker函数中,传递的参数(颜色)已经是相应标记的 ID,这意味着您不需要将其传递给linkColor功能。这是更改后的标记函数:

function marker(color) {
    svg.append("svg:marker")
      ...
      .attr("refX", 10)
      ...
      .style("fill", color);

    return "url(" + color + ")";
  };

这是使用上面代码的片段,为了回答您关于如何添加 JSON 的评论,您可以将其添加为变量(正如我在这里所做的那样,这也使得调试更容易)。

var width = 960,
height = 500;

// initialization
var svg = d3.select("div").append("svg")
    .attr("width", width)
    .attr("height", height);

var force = d3.layout.force()
    .gravity(0) // atom's cohesiveness / elasticity of imgs :)
    .distance(150) // how far the lines ---> arrows :)
    .charge(-50) // meta state transition excitement
    .linkDistance(140)
    //.friction(0.55) // similar to charge for quick reset :)
    .size([width, height]); // degree of freedom to the canvas

// exception handling

var json =     {
  "nodes": [
    {"x": 100, "y": 100},
    {"x": 250, "y": 100},
    {"x": 400, "y": 100},
    {"x": 550, "y": 200},
    {"x": 700, "y": 200},
    {"x": 100, "y": 300},
    {"x": 250, "y": 300},
    {"x": 400, "y": 300}
  ],
  "links": [
    {"source":  0, "target":  1, "colorCode" : "ctof"},
    {"source":  1, "target":  2, "colorCode" : "ftoc"},
    {"source":  2, "target":  3, "colorCode" : "ctof"},
    {"source":  3, "target":  4, "colorCode" : "ftoc"},
    {"source":  5, "target":  6, "colorCode" : "ctof"},
    {"source":  6, "target":  7, "colorCode" : "ftoc"},
    {"source":  7, "target":  3, "colorCode" : "ctof"}
  ]
};

    force
      .nodes(json.nodes)
      .links(json.links)
      .start();

      // Build the link
      var link = svg.selectAll(".links")
      .data(json.links)
      .enter().append("line")
      .attr("class", "lol")
      .style("stroke-width", "2")
      .attr("stroke", function(d){
        return linkColor(d.colorCode);})
      .each(function(d) {
        var color = linkColor(d.colorCode);
        d3.select(this).attr("marker-end", marker(color));
      });

      function marker(color) {
        svg.append("svg:marker")
          .attr("id", color.replace("#", ""))
          .attr("viewBox", "0 -5 10 10")
          .attr("refX", 10)
          .attr("refY", 0)
          .attr("markerWidth", 9)
          .attr("markerHeight", 9)
          .attr("orient", "auto")
          .attr("markerUnits", "userSpaceOnUse")
          .append("svg:path")
          .attr("d", "M0,-5L10,0L0,5")
          .style("fill", color);

        return "url(" + color + ")";
      };
      var node = svg.selectAll(".nodes")
      .data(json.nodes)
      .enter().append("g")
      .attr("class", "node")
      .call(force.drag);

      node.append("svg:image")
                  .attr("xlink:href", "") // update the node with the image
                  .attr("x", function(d) { return -5;}) // how far is the image from the link??
                  .attr("y", function(d) { return -25;}) // --- same ---
                  .attr("height", 55) // size
                  .attr("width", 55);

      // Define the div for the tooltip
      var div = d3.select("body").append("pre")
      .attr("class", "tooltip")
      .style("opacity", 0);

      node.append("text")
        .attr("class", "labelText")
        .attr("x", function(d) { return -5;})
        .attr("y", function(d) { return 48;})
        .text(function(d) { return d.label });

      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 + ")"; });

        force.stop();
      });

      function linkColor(linkCode) {
        switch (linkCode)
        {
          case 'ctoc':
            return '#0000FF';//blue
            break;
          case 'ctof':
            return '#00afaa';//green
            break;
          case 'ftoc':
            return '#fab800';//yellow
            break;
          case 'ftof':
            return '#7F007F';//purple
            break;
          default:
            return '#0950D0';//generic blue
            break;
        }
      }
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://d3js.org/d3.v3.min.js"></script>
  </head>

  <body>
      <div></div>
      
          <script src="script.js"></script>

  </body>

我又做了一个改变(改变了refY根据箭头长度为 10)。尝试一下看看有什么不同。 希望这可以帮助。

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

D3 js图中相同颜色的箭头和链接 的相关文章

随机推荐

  • 我可以将 Android 中的默认推送通知图标从应用程序图标覆盖为自定义图标吗?

    我可以将 Android 中的默认推送通知图标从应用程序图标覆盖为自定义图标吗 当推送通知出现时 我正在使用默认的 firebase 实现在系统托盘中显示通知 由于我的应用程序图标是彩色的并且具有渐变 因此当通知到来时 android尝试制
  • 以编程方式模拟 Android 按钮点击 [重复]

    这个问题在这里已经有答案了 我见过this https stackoverflow com questions 4553374 how to simulate a button click through code in android r
  • Tkinter.text - 如何计算动态字符串的高度?

    我有一个Text包含自定义字符串的小部件 n字符 多行 该小部件放置在垂直方向内panedwindow我想调整panedwindow的窗框显示整个字符串Text widget 该字符串本质上是动态的 这意味着它正在通过我的应用程序中的其他方
  • Qt:在整个表单上应用字体更改

    我有许多使用 Qt Designer 创建的表单 Qt 4 8 我想从某个地方更改所有表单的字体 在 Windows 中 QApplication setFont font 工作完美 不幸的是 似乎有一个错误 我不知道这是否错误报告 htt
  • 下拉菜单填充相同的列表项

    我有一个 Gridview 其中有两个下拉列表模板字段 我在运行时将它们绑定到相同的列表项 li new listitem 1 1 dl1 items add li dl2 items add li li new listitem 2 2
  • 如何将 Windows cmd stdout 和 stderr 重定向到单个文件?

    我正在尝试重定向 a 的所有输出 stdout stderr Windows命令 https learn microsoft com en us windows server administration windows commands
  • Django:如何聚合/注释多对多关系?

    我有一个 Person 模型和一个 Tag 模型 它们之间有一个 m2m 我需要提取与给定人员查询集中最多记录相关的标签以及计数 有没有一种优雅 有效的方法来使用 Django ORM 提取它 更好的是 有没有办法通过一些注释来获取整个标签
  • 如何确定 Google Play 服务的版本?

    我正在从 Eclipse 迁移到 Android Studio 我有一个导入到 Android Studio 中的项目 该项目使用 Google Play 服务 因此我遵循在这里找到的文档 http developer android co
  • 清除 NSTableView 内容

    我有一个NSTableView里面充满了来自程序的数据 我有一个重置按钮 除了用于程序的其他部分之外 should清除NSTableView的数据 但是 我完全不知道该怎么做 我还在学习 Obj C 您可以通过调用从 NSTableView
  • Observable 终于订阅了

    根据本文 http paqmind com posts rxjs error and completed events demystified onComplete and onError的功能subscribe是互斥的 意思是要么onEr
  • 如何在rails中的text_area_tag中插入占位符文本?

    我正在使用以下代码来生成textarea tag 渲染后 它会生成以下 HTML
  • Excel 文件 - 它已被其他用户以独占方式打开,

    我正在使用 C 读取 excel 文件 下面是按预期工作的代码 除了每次运行应用程序时 我都必须关闭 excel 文件 否则我会收到以下错误消息 The Microsoft Access database engine cannot ope
  • 在 Cocoa Touch 中以编程方式切换视图

    如何在 iPhone 应用程序中以编程方式更改屏幕视图 我已经能够创建导航视图并以编程方式推送 弹出它们以产生此行为 但如果我想简单地更改当前视图 不使用 UINavigation 控制器对象 那么实现此目的的最简洁方法是什么 一个简单的示
  • 如何让函数 [a] -> [a] 对 [(a,Int)] 进行操作?

    我发现自己经常按照以下模式编写代码 foo xs map snd filter lt 10 fst zip xs 0 bar ys map snd sortBy compare on fst zip ys 0 现在我想把它抽象出来 foo
  • Kubernetes:如何获取运行超过 3 天的命名空间?

    示例 我想获取所有运行超过 3 天的命名空间 我已经借助此命令按标签和创建时间戳对命名空间进行了排序 kubectl get 命名空间 l Provisioner foo sort by metadata creationTimestamp
  • 如何在不同的命名空间上使用 nginx 入口 TCP 服务[重复]

    这个问题在这里已经有答案了 我在 kubernetes 集群中部署了两个命名空间 命名空间 A 主机 mysql 和命名空间 B 运行 postgress 并在这些端口上公开其服务部署 Namespace A mysql port 3306
  • JScrollPane 垂直滚动条太宽

    我正在使用 Netbeans GUI Builder 创建 GUI 应用程序 因此生成的所有代码都是由 Netbeans 生成的 预览设计中的一切看起来都很好 但是当我运行应用程序时 JScrollPane 显示得很糟糕 如您所见 只有一半
  • 在VB6中将十六进制值转换为十进制值

    在VB6中如何将十六进制值转换为十进制值 我只是想看看这是否有效 Dim hexVal as string hexVal 7B19AB clng H hexVal 然而 我得到 类型不匹配 error 去掉 号 Dim hexVal as
  • CSS 中的美女图标形状

    如何仅在 CSS 中绘制此 Belle 图标形状 我已经尝试过方形元素上的边框半径 但没有得到确切的角 那么 为了达到准确的效果 即使我们使用百分比 我们也不能依赖单个元素border radius 因此 一种选择可能是使用两个彼此重叠的
  • D3 js图中相同颜色的箭头和链接

    我是 D3 的新手 一直在尝试使箭头的颜色与 D3 图中箭头的颜色相同 参考给出的代码解决方案here https stackoverflow com questions 32964457 match arrowhead color to