根据所选数据更改Y轴范围

时间:2016-05-20 14:48:57

标签: javascript d3.js

我在D3中完成了图表。它有效,但我想添加轴缩放的能力。

我有几组具有完全不同范围的数据。 所以我希望根据所选系列改变Y轴范围。

这是整个代码:https://plnkr.co/edit/89ERO3GuxREvYQ3DRX5L?p=preview

目前链接的示例有4个系列:我希望如果用户选择“Kiwi”和“Apple”,那么Y轴的范围为[0-1]而不是[0-15](或类似的东西)。 重要的是根据所选数据更改范围。

我的意思是http://bl.ocks.org/andrewleith/3824854

为此,我想在数组中保存具有不透明度0.5或1(可见线)的标签,然后根据更改域Y. 我创建了数组,然后我尝试以这种方式识别不透明度为0.5的标签(为简单起见):

var actives = new Array();
var activeElem = d3.select(".line").attr("opacity", 0.5);
console.log(activeElem);

var actives = new Array();
var activeElem = d3.selection.style({opacity: "0.5"});
console.log(activeElem);

var actives = new Array();
var activeElem = d3.selectAll("path[opacity='0.5']");
console.log(activeElem);

这些都不起作用。 我也做了其他测试,但我不记得究竟是什么,但仍然无法正常工作。 我疯了。

选择不透明度为0.5和1的项目并根据所选数据更改Y轴的正确方法是什么?

谢谢

1 个答案:

答案 0 :(得分:0)

这里的主要问题是您需要再次计算数据的最小值和最大值,然后使用最小值和最大值更新您的yAxis。

// find the new max value of the selected series
var max = d3.max(filteredData, function(d) {
    return d3.max(d.values, function(e) {
      return e.value;
    });
});
// find the new min value of the selected series
var min = d3.min(filteredData, function(d) {
    return d3.min(d.values, function(e) {
        return e.value;
    });
});
// set the new y domain
y.domain([min, max]);
// update our new y axis with the new domain
svg.selectAll("g .y.axis").transition()
    .duration(800).call(yAxis);

由于您希望通过选择某些行来过滤数据,我建议使用data功能,这样您就可以使用当前选择加入指定的数据数组(更多信息here)。当您使用d3实用程序时,您正在进行巨大的forEach循环。有些东西:

// apend a group element which will contain our lines
svg.append('g')
   .attr('class', 'line-container')
   .selectAll('.normal-line-paths')
   .data(dataNest) // set our data
   .enter() // enter the data and start appending elements
   .append('path')
   .call(path); // calling our path function for later use when appending lines

我修改了您的代码以使用更多文档驱动的方法,您可以单击标签,y轴将相应地缩放过滤数据集的新的最小值和最大值。我将虚线组留空,这样您就可以尝试编写其余部分并了解数据连接背后的逻辑。

https://plnkr.co/edit/Wso0Gu4yHkdsHhl8NY8I?p=preview

编辑:

这是带有虚线的plnkr:)

https://plnkr.co/edit/yHGGtrLXZyyq0KpiVWYf?p=preview