这次我试图创建一个带有可切换系列的堆叠条 – 基于Mike Bostock的例子(再次感谢Mike!)我已经成功地使它具有响应性和可缩放性,通过传奇的可切换系列是剩下的最后一件事.
我创建了图例项目,并使用键应用了正确的颜色:
- var legendItem = d3.select(".legend")
- .selectAll("li")
- .data(keys)
- .enter()
- .append("li")
- .on('click',function(d) {
- keys.forEach(function(c) {
- if (c != d) tKeys.push(c)
- });
- fKeys = tKeys;
- tKeys = [];
- redraw();
- });
- legendItem
- .append("span")
- .attr("class","color-square")
- .style("color",function(d) {
- return colorScale5(d);
- });
- legendItem
- .append("span")
- .text(function(d) {
- return (d)
- });
根据结构,为了创建可切换的项目,我得出的结论是,我必须能够从键和数据集切换它 – 或者还有另一种方法吗?我已设法从键中删除特定键,但不是从数据集中删除,我不知道如何正确映射它.
第二个问题是我无法找到切换密钥的方法,只是将其删除即可.这是原始数据集:
- var data = [{
- "country": "Greece","Vodafone": 57,"Wind": 12,"Cosmote": 20
- },{
- "country": "Italy","Vodafone": 40,"Wind": 24,"Cosmote": 35
- },{
- "country": "France","Vodafone": 22,"Wind": 9,"Cosmote": 9
- }]
在从嵌套数据集提供的值中,我可以将名为“enabled”的键附加到每个对象,并且可以轻松地过滤数据集,但无法弄清楚如何附加键以帮助进行过滤过程.
edit3从问题中删除了无用的信息:
这是一个工作小提琴:
https://jsfiddle.net/fgseaxoy/2/
解决方法
SergGr的代码效果很好,但有些部分可以更干净.
的onclick
- var fKeys = keys.slice();
- //a helper object to record the state of keys
- var fKeyReference = fKeys.map(function () {
- return true; //used to indicate if the corresponding key is active
- });
- function getActiveKeys(reference) {
- return reference.map(function (state,index) {
- if (state) {
- return keys[index]; //just keep keys whoes state is true
- }
- return false; //return false to be filered
- }).filter(function (name) {
- return name
- });
- }
- ...
- .on('click',function (d) {
- if (fKeys.length === 1 && fKeys[0] === d) {
- return;
- }
- var index = keys.indexOf(d);
- fKeyReference[index] = !fKeyReference[index]; // toggle state of fKeyReference
- fKeys = getActiveKeys(fKeyReference);
- redraw();
- });
.堆()
- g.selectAll(".d3-group").remove();//remove all groups and draw them all again
- stackedBars = g
- .selectAll(".d3-group")
- .data(d3.stack().keys(fKeys)(dataset));
更新轴(y.domain)
- y.domain([
- 0,1.2 * d3.max(dataset,function (d) {
- return fKeys.reduce(function (pre,key) {//calculate the sum of values of fKeys
- return pre + d[key];
- },0);
- })
- ]);
最后,jsfiddle