How to fill half of the rectangle with color in d3

2019-09-18 01:34发布

Hi want a rectangle of width 250, and i want to fill the rectangle with the color based on the input value.I tried to create one rectangle of gray and another one of color skyblue on the same position to acheive this but it update the rectangle only. cant create another rectangle on the previous one. what to do.? My Js fiddle is http://jsfiddle.net/sSqmV/ i want to create an second rectangle of sky blue over the previous one of white color to acheive my task.

  var chart = d3.select("div.dev1").append("svg")
    .attr("width", 292)
    .attr("height", 300);
        var dataset = [0, 1, 2];
        var dataset2 = [0, 1, 2,3];

       var rects1 = chart.selectAll("rect")
        .data(dataset)
        .enter()
        .append("rect")
        .attr("x", 10)
        .attr("y", function (d, i) { return (i + 1) * 60; })
        .attr("height", 6)
        .attr("width", 250)
        .attr("fill", "white");


        var rects = chart.selectAll("rect")
        .data(dataset2)
        .enter()
        .append("rect")
        .attr("x", 10)
        .attr("y", function (d, i) { return (i + 1) * 60; })
        .attr("height", 6)
        .attr("width", 250)
        .attr("fill", "skyblue");

        var texts = chart.selectAll("text").data(dataset2).enter().append("text")
            .text("18% of the questions were ANSWERED")
        .attr("x", 10)
        .attr("y", function (d, i) { return 90+(i*60); });

1条回答
在下西门庆
2楼-- · 2019-09-18 01:42

You can do something like this:

 var chart = d3.select("div.dev1").append("svg")
     .attr("width", 292)
     .attr("height", 300);
 var dataset = [0, 1, 2];
 var dataset2 = [0, 1, 2, 3];




 var rects = chart.selectAll(".rect1")
     .data(dataset2)
     .enter()
     .append("rect")
     .attr('class', 'rect1')
     .attr("x", 10)
     .attr("y", function (d, i) {
     return (i + 1) * 60;
 })
     .attr("height", 6)
     .attr("width", 250)
     .attr("fill", "skyblue");

 var rects1 = chart.selectAll(".rect")
     .data(dataset)
     .enter()
     .append("rect")
     .attr('class', 'rect')
     .attr("x", 10)
     .attr("y", function (d, i) {
     return (i + 1) * 60;
 })
     .attr("height", 6)
     .attr("width", 125)
     .attr("fill", "white");




 var texts = chart.selectAll("text").data(dataset2).enter().append("text")
     .text("18% of the questions were ANSWERED")
     .attr("x", 10)
     .attr("y", function (d, i) {
     return 90 + (i * 60);
 });

Here is jsfiddle: http://jsfiddle.net/cuckovic/sSqmV/2/

查看更多
登录 后发表回答