简体   繁体   English

在树形图d3.js中解析json以获取不同的颜色

[英]Parse json in Tree map d3.js to get different colours

I have followed this link for reference 我已点击链接以供参考

But the json in this link is different. 但是此链接中的json不同。 I want to parse: 我想解析:

[
    {\"name\":\"ABC\",\"amount\":489956},
    {\"name\":\"XYZ\",\"amount\":54554726}
]

I have tried using this code: 我尝试使用此代码:

     var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg
            .attr("height");

    var fader = function(color) {
        return d3.interpolateRgb(color, "#fff")(0.2);
    }, color = d3.scaleOrdinal(d3.schemeCategory20.map(fader)), format = d3
            .format(",d");

    var treemap = d3.treemap().tile(d3.treemapResquarify).size(
            [ width, height ]).round(true).paddingInner(1);

  var jsonResp = "{\"name\": \"schools\",\"children\":[{\"name\":\"ABC\",\"amount\":489956},{\"name\":\"XYZ\",\"amount\":54554726}]}";

    var data = JSON.parse(jsonResp);    
    var root = d3.hierarchy(data).eachBefore(
                function(d) {
                    d.data.id = (d.parent ? d.parent.data.id + "." : "")
                            + d.data.name;
                }).sum(sumBySize).sort(function(a, b) {
            return b.height - a.height || b.value - a.value;
        });

        treemap(root);

        var cell = svg.selectAll("g").data(root.leaves()).enter().append(
                "g").attr("transform", function(d) {
            return "translate(" + d.x0 + "," + d.y0 + ")";
        });

        cell.append("rect").attr("id", function(d) {
            return d.data.id;
        }).attr("width", function(d) {
            return d.x1 - d.x0;
        }).attr("height", function(d) {
            return d.y1 - d.y0;
        }).attr("fill", function(d) {
            return color(d.parent.data.id);
        });

        cell.append("clipPath").attr("id", function(d) {
            return "clip-" + d.data.id;
        }).append("use").attr("xlink:href", function(d) {
            return "#" + d.data.id;
        });

        cell.append("text").attr("clip-path", function(d) {
            return "url(#clip-" + d.data.id + ")";
        }).selectAll("tspan").data(function(d) {
            return d.data.name.split(/(?=[A-Z][^A-Z])/g);
        }).enter().append("tspan").attr("x", 4).attr("y", function(d, i) {
            return 13 + i * 10;
        }).text(function(d) {
            return d;
        });

        cell.append("title").text(function(d) {
            return  "Amount - "+format(d.value)+" ";
        });

        d3.selectAll("input").data([ sumBySize, sumByCount ], function(d) {
            return d ? d.name : this.value;
        }).on("change", changed);

        var timeout = d3.timeout(function() {
            d3.select("input[value=\"sumByCount\"]").property("checked",
                    true).dispatch("change");
        }, 2000);

        function changed(sum) {
            timeout.stop();
            treemap(root.sum(sum));
            cell.transition().duration(750).attr("transform", function(d) {
                return "translate(" + d.x0 + "," + d.y0 + ")";
            }).select("rect").attr("width", function(d) {
                return d.x1 - d.x0;
            }).attr("height", function(d) {
                return d.y1 - d.y0;
            });
        }
    });

    function sumBySize(d) {
        return d.amount;
    } 

But I am getting same colour for all objects in the parsed json. 但是我为解析的json中的所有对象都获得了相同的颜色。 I want to have different colors for each object without changing the structure of aforementioned json. 我希望每个对象都具有不同的颜色,而无需更改上述json的结构。 How to change the parsing in the code to obtain different colors for each object? 如何更改代码中的解析以获得每个对象的不同颜色?
I need to categorise the amount in json as well as Crores or Lakhs based on digits and display it on hover. 我需要根据数字对json以及Crores或Lakhs中的金额进行分类,并将其显示在悬停上。 I am just a beginner in d3.js. 我只是d3.js的初学者。

First of all there are several issues with the code you provided : 首先,您提供的代码存在几个问题:

  • You removed d3.json("flare.json", function(error, data) { from the original code, but forgot to remove the closing }); 您从原始代码中删除了d3.json("flare.json", function(error, data) { ,但忘记删除了结束d3.json("flare.json", function(error, data) { }); resulting in an error 导致错误
  • You removed the definition of sumByCount which is used in the rest of the code, resulting in an other error 您删除了其余代码中使用的sumByCount的定义,从而导致另一个错误

Onto your color problem, the color of the rectangle is set here : 关于颜色问题,在此处设置矩形的颜色:

cell.append("rect").attr("id", function(d) {
            return d.data.id;
        }).attr("width", function(d) {
            return d.x1 - d.x0;
        }).attr("height", function(d) {
            return d.y1 - d.y0;
        }).attr("fill", function(d) {
            return color(d.parent.data.id);
        });

it's controlled by the fill attribute. 它由fill属性控制。 Which means there is probably an issue with d.parent.data.id 这意味着d.parent.data.id可能存在问题

d here is an element of the array root.leaves() if you print this out in the console, you'll see that d.parent.data.id match 'schools' for each element. 如果在控制台中将其打印出来,则d是数组root.leaves()的元素,您会看到d.parent.data.id与每个元素的'schools'相匹配。 Which is why the color scale returns the same color. 这就是色标返回相同颜色的原因。

If you use d.data.id directly, with the html from the example with your data, you end up with a working code (with root.leaves() printed out) : 如果直接使用d.data.id ,将示例中的html与您的数据一起使用,您将得到一个有效的代码(打印出root.leaves() ):

 var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg .attr("height"); var fader = function(color) { return d3.interpolateRgb(color, "#fff")(0.2); }, color = d3.scaleOrdinal(d3.schemeCategory10.map(fader)), format = d3 .format(",d"); var treemap = d3.treemap().tile(d3.treemapResquarify).size( [width, height]).round(true).paddingInner(1); var jsonResp = "{\\"name\\": \\"schools\\",\\"children\\":[{\\"name\\":\\"ABC\\",\\"amount\\":489956},{\\"name\\":\\"XYZ\\",\\"amount\\":54554726}]}"; var data = JSON.parse(jsonResp); var root = d3.hierarchy(data).eachBefore( function(d) { d.data.id = (d.parent ? d.parent.data.id + "." : "") + d.data.name; }).sum(sumBySize).sort(function(a, b) { return b.height - a.height || b.value - a.value; }); treemap(root); console.log(data); console.log(root.leaves()); var cell = svg.selectAll("g").data(root.leaves()).enter().append( "g").attr("transform", function(d) { return "translate(" + d.x0 + "," + d.y0 + ")"; }); cell.append("rect").attr("id", function(d) { return d.data.id; }).attr("width", function(d) { return d.x1 - d.x0; }).attr("height", function(d) { return d.y1 - d.y0; }).attr("fill", function(d) { return color(d.data.id); }); cell.append("clipPath").attr("id", function(d) { return "clip-" + d.data.id; }).append("use").attr("xlink:href", function(d) { return "#" + d.data.id; }); cell.append("text").attr("clip-path", function(d) { return "url(#clip-" + d.data.id + ")"; }).selectAll("tspan").data(function(d) { return d.data.name.split(/(?=[AZ][^AZ])/g); }).enter().append("tspan").attr("x", 4).attr("y", function(d, i) { return 13 + i * 10; }).text(function(d) { return d; }); cell.append("title").text(function(d) { return "Amount - " + format(d.value) + " "; }); d3.selectAll("input").data([sumBySize, sumByCount], function(d) { return d ? d.name : this.value; }).on("change", changed); var timeout = d3.timeout(function() { d3.select("input[value=\\"sumByCount\\"]").property("checked", true).dispatch("change"); }, 2000); function changed(sum) { timeout.stop(); treemap(root.sum(sum)); cell.transition().duration(750).attr("transform", function(d) { return "translate(" + d.x0 + "," + d.y0 + ")"; }).select("rect").attr("width", function(d) { return d.x1 - d.x0; }).attr("height", function(d) { return d.y1 - d.y0; }); } function sumByCount(d) { return d.children ? 0 : 1; } function sumBySize(d) { return d.amount; } 
 <svg width="960" height="570"></svg> <form> <label><input type="radio" name="mode" value="sumBySize" checked> Size</label> <label><input type="radio" name="mode" value="sumByCount"> Count</label> </form> <script src="https://d3js.org/d3.v4.min.js"></script> 

However this is a quick fix, as I don't have the time to completely analyze what's happening here.I think you should spend some time trying to understand completely the code from the link you provided, or you might run into many other issues. 但是,这是一个快速修复方法,因为我没有时间完全分析这里发生的事情。我认为您应该花一些时间尝试从提供的链接中完全理解代码,否则您可能会遇到许多其他问题。 Copy pasting something you don't completely understand will usually result in hours of painful debugging ;) 复制粘贴您不完全了解的内容通常会导致数小时的痛苦调试;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM