如何在d3.js中用颜色填充矩形的一半 [英] How to fill half of the rectangle with color in d3.js

查看:2769
本文介绍了如何在d3.js中用颜色填充矩形的一半的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望一个宽度为250的矩形,我想根据输入值填充颜色的矩形。我试图在相同的位置创建一个灰色矩形和另一个天蓝色的矩形,但它仅更新矩形。不能在前一个矩形上创建另一个矩形。该怎么办。?我的Js小提琴是 http://jsfiddle.net/sSqmV/ 我想创建一个天蓝色的第二个矩形在上一个白色以上,以便我的任务。

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


推荐答案

您可以这样做:

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

这里是jsfiddle: http://jsfiddle.net/cuckovic/sSqmV/2/

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

这篇关于如何在d3.js中用颜色填充矩形的一半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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