How to fill half of the rectangle with color in d3.js

前提是你 提交于 2019-12-11 19:03:55

问题


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:


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/



来源:https://stackoverflow.com/questions/23623959/how-to-fill-half-of-the-rectangle-with-color-in-d3-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!