如何为D3 Sequence Sunburst创建图例? [英] How to create legend for D3 Sequence Sunburst?

查看:88
本文介绍了如何为D3 Sequence Sunburst创建图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改原始D3 Sequence Sunburst文件以使其更适合我的需求.原始的colors变量是硬编码的对象.显然这不是最好的方法.我正在使用flare.json示例,该示例更大,更难阅读,但仍然比经过测试后将要使用的json文件小得多.

我想随机生成颜色,将它们应用于createvisualization函数中的每个基准,但是我是D3的新手,并且不知道如何1)从中获取名称(除了叶子以外的所有东西) json文件,然后2)将它们与随机颜色配对.

添加随机颜色并应用它们是微不足道的,

var colors = d3.scale.category10();
...
.style("fill", function(d,i) { return colors(i); })

但是我仍然要注意确保如何在json中获取所有非叶子的名称,然后根据随机颜色和非叶子创建一个数组.

非常感谢您的帮助.

解决方案

要获取所有非叶元素的名称,可以执行以下操作.

var names = [];

function getNames(node) {
  if(node.children) {
    names.push(node.name);
    node.children.forEach(function(c) { getNames(c); });
  }
}

getNames(root);

运行此代码后,names将包含您想要的所有名称.要从中生成图例,可以使用names数组作为数据:

var gs = svg.selectAll("g.name").data(names).enter().append("g").attr("class", "name");
gs.append("rect")
  // set position, size etc
  .attr("fill", d);
gs.append("text")
  // set position etc
  .text(String);

这将为每个名称附加一个g元素,并在每个g元素内,附加一个rect并填充与该名称对应的颜色,该text元素则显示该名称. >

I'm modifying the original D3 Sequence Sunburst file to better suit my needs. The original colors variable is a hard-coded object. This clearly cannot be the best method. I'm using the flare.json example, which is larger, harder to read, and still much smaller than the json file I will be user after testing.

I'd like to randomly generate colors, apply them to each datum in the createvisualization function, but I'm new to D3, and do not know how to 1) fetch names (everything but the leaves) from the json file, and 2) pair them with their random color.

Edit:

Adding random colors and applying them turned out to be trivial,

var colors = d3.scale.category10();
...
.style("fill", function(d,i) { return colors(i); })

But I'm still note sure how to fetch the names of all non-leaves in the json, then create an array from both the random colors and the non-leaves.

Help here greatly appreciated.

解决方案

To get the names of all non-leaf elements, you can do something like this.

var names = [];

function getNames(node) {
  if(node.children) {
    names.push(node.name);
    node.children.forEach(function(c) { getNames(c); });
  }
}

getNames(root);

After running this code, names will contain all the names you want. To then generate a legend from that, you can use the names array as the data:

var gs = svg.selectAll("g.name").data(names).enter().append("g").attr("class", "name");
gs.append("rect")
  // set position, size etc
  .attr("fill", d);
gs.append("text")
  // set position etc
  .text(String);

This will append a g element for each name and within each g element, append a rect that is filled with the colour corresponding to the name and a text element that shows the name.

这篇关于如何为D3 Sequence Sunburst创建图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆