新来的。我正在使用D3,基本上我有两个数组形式的数据集。我想要实现的是按下按钮,新数据集将覆盖旧数据集(我已经实现了这一点),然后绑定新数据集并重新绘制堆积的条形图。这对我来说不会发生。按下按钮时,只删除几个条形。
会感激任何提示。我认为这很尴尬,因为我使用堆积条形图而不是普通条形图。 谢谢! :)
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
// .ticks(5);
//Width and height
var w = 600;
var h = 300;
var barPadding = 50;
//Original data
var dataset = [
[
{ y: 20 }, //male
{ y: 4 },
{ y: 16},
{ y: 53},
{ y: 15 }
],
[
{ y: 12 }, //female
{ y: 4 },
{ y: 3 },
{ y: 36 },
{ y: 2 }
],
];
console.log(dataset);
// var myDataSet = dataset;
// var totalDeaths = d.y0 + d.y1;
//Set up stack method
var stack = d3.layout.stack();
//Data, stacked
stack(dataset);
//Set up scales
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset[0].length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0,
d3.max(dataset, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
})
])
.range([0, h]);
//Easy colors accessible via a 10-step ordinal scale
// var colors = d3.scale.category20c();
var color = d3.scale.ordinal()
.domain(["Male", "Female"])
.range(["#00B2EE", "#FF69B4"]);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
// Add a group for each row of data
var groups = svg.selectAll("g")
.data(dataset)
.enter()
.append("g")
.style("fill", function(d, i) {
return color(i);
});
// Add a rect for each data value
var rects = groups.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.on("mouseover", function(d) {
//Get this bar's x/y values, then augment for the tooltip
var xPosition = parseFloat(d3.select(this).attr("x")) + xScale.rangeBand() / 2;
var yPosition = parseFloat(d3.select(this).attr("y")) + 14;
//Create the tooltip label
svg.append("text")
.attr("id", "tooltip")
.attr("x", xPosition)
.attr("y", yPosition)
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("font-weight", "bold")
.attr("fill", "black")
.html("Female deaths: " + d.y + "\n" + " \nMale deaths: " + d.y0);
})
.on("mouseout", function() {
//Remove the tooltip
d3.select("#tooltip").remove();
})
.attr("width", xScale.rangeBand())
.attr("y", function(d) {
return h - yScale(d.y0) - yScale(d.y) ;
})
.attr("height", function(d) {
return yScale(d.y);
});
d3.select("#target")
.on("click", function() { //event listener on button click
// alert("heeeey");
//New values for dataset
dataset = [
[
{ y: 100 }, //male
{ y: 20 },
{ y: 16},
{ y: 53},
{ y: 15 }
],
[
{ y: 5 }, //female
{ y: 4 },
{ y: 3 },
{ y: 36 },
{ y: 2 }
],
];
console.log(dataset);
//Data, stacked
// stack(dataset);
//Update all rects
var gas = svg.selectAll("rect")
.data(dataset)
// .transition()
// .duration(1000)
// .ease("cubic-in-out")
.attr("width", xScale.rangeBand())
.attr("y", function(d) {
return h - yScale(d.y0) - yScale(d.y) ;
})
.attr("height", function(d) {
return yScale(d.y);
})
.attr("x", function(d, i) {
return xScale(i);
});
});