javascript – d3.js叠加栏与切换系列

前端之家收集整理的这篇文章主要介绍了javascript – d3.js叠加栏与切换系列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这次我试图创建一个带有可切换系列的堆叠条 – 基于Mike Bostock的例子(再次感谢Mike!)我已经成功地使它具有响应性和可缩放性,通过传奇的可切换系列是剩下的最后一件事.

我创建了图例项目,并使用键应用了正确的颜色:

  1. var legendItem = d3.select(".legend")
  2. .selectAll("li")
  3. .data(keys)
  4. .enter()
  5. .append("li")
  6. .on('click',function(d) {
  7. keys.forEach(function(c) {
  8. if (c != d) tKeys.push(c)
  9. });
  10. fKeys = tKeys;
  11. tKeys = [];
  12. redraw();
  13. });
  14.  
  15. legendItem
  16. .append("span")
  17. .attr("class","color-square")
  18. .style("color",function(d) {
  19. return colorScale5(d);
  20. });
  21.  
  22. legendItem
  23. .append("span")
  24. .text(function(d) {
  25. return (d)
  26. });

根据结构,为了创建可切换的项目,我得出的结论是,我必须能够从键和数据集切换它 – 或者还有另一种方法吗?我已设法从键中删除特定键,但不是从数据集中删除,我不知道如何正确映射它.

第二个问题是我无法找到切换密钥的方法,只是将其删除即可.这是原始数据集:

  1. var data = [{
  2. "country": "Greece","Vodafone": 57,"Wind": 12,"Cosmote": 20
  3. },{
  4. "country": "Italy","Vodafone": 40,"Wind": 24,"Cosmote": 35
  5. },{
  6. "country": "France","Vodafone": 22,"Wind": 9,"Cosmote": 9
  7. }]

在从嵌套数据集提供的值中,我可以将名为“enabled”的键附加到每个对象,并且可以轻松地过滤数据集,但无法弄清楚如何附加键以帮助进行过滤过程.

edit3从问题中删除了无用的信息:

这是一个工作小提琴:
https://jsfiddle.net/fgseaxoy/2/

解决方法

SergGr的代码效果很好,但有些部分可以更干净.

的onclick

  1. var fKeys = keys.slice();
  2.  
  3. //a helper object to record the state of keys
  4. var fKeyReference = fKeys.map(function () {
  5. return true; //used to indicate if the corresponding key is active
  6. });
  7.  
  8. function getActiveKeys(reference) {
  9. return reference.map(function (state,index) {
  10. if (state) {
  11. return keys[index]; //just keep keys whoes state is true
  12. }
  13. return false; //return false to be filered
  14. }).filter(function (name) {
  15. return name
  16. });
  17. }
  18.  
  19. ...
  20. .on('click',function (d) {
  21. if (fKeys.length === 1 && fKeys[0] === d) {
  22. return;
  23. }
  24.  
  25. var index = keys.indexOf(d);
  26. fKeyReference[index] = !fKeyReference[index]; // toggle state of fKeyReference
  27. fKeys = getActiveKeys(fKeyReference);
  28. redraw();
  29. });

.堆()

  1. g.selectAll(".d3-group").remove();//remove all groups and draw them all again
  2. stackedBars = g
  3. .selectAll(".d3-group")
  4. .data(d3.stack().keys(fKeys)(dataset));

更新轴(y.domain)

  1. y.domain([
  2. 0,1.2 * d3.max(dataset,function (d) {
  3. return fKeys.reduce(function (pre,key) {//calculate the sum of values of fKeys
  4. return pre + d[key];
  5. },0);
  6. })
  7. ]);

最后,jsfiddle

猜你在找的JavaScript相关文章