你想要一个宽度为250的矩形,我想用基于输入值的颜色填充矩形。我试图在同一位置创建一个灰色矩形和另一个颜色天蓝色来实现这个但是它仅更新矩形。不能在前一个矩形上创建另一个矩形。该怎么办。?我的Js小提琴是http://jsfiddle.net/sSqmV/我想在前一个白色上创建第二个天蓝色矩形,以实现我的任务。
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); });
答案 0 :(得分:3)
您可以这样做:
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/