【问题标题】:Update the y-axis of a brushed area chart更新拉丝区域图的 y 轴
【发布时间】:2012-12-20 15:19:47
【问题描述】:

我正在使用 d3.js,我正在通过修改 this example 来制作拉丝面积图。除了根据画笔改变 x 轴之外,我还希望根据画笔内数据的 y 值重新绘制图表的 y 轴(类似于a Google Finance chart 的行为)。

我已经使该功能正常工作,但只是以某种方式使画笔能够在 x 和 y 空间中绘制。为此,我首先向 brush 变量添加了一个 y 比例:

var brush = d3.svg.brush()
    .x(x2)
    .y(y2)
    .on("brush", brush);

这使得brush.extent() 返回以下多维数组:[ [x0, y0], [x1, y1] ]。然后我在brush() 函数中使用这些数据来重新定义焦点图表的 x 和 y 域:

function brush() {
  var extent = brush.extent();
  x.domain(brush.empty() ? x2.domain() : [ extent[0][0], extent[1][0] ]);
  y.domain(brush.empty() ? y2.domain() : [ extent[0][1], extent[1][1] ]);
  focus.select("path").attr("d", area);
  focus.select(".x.axis").call(xAxis);
  focus.select(".y.axis").call(yAxis);
}

这可行,但是通过在画笔变量中定义 y 比例,用户现在可以在焦点图表中拖动“框”,而不是像原始图表中那样只能从西向东拖动。

基本上,我的问题是:我如何获得落在画笔区域内的值范围,而不是画笔区域本身的范围?这甚至可能吗?

d3的刷机文档是here

【问题讨论】:

    标签: d3.js brush


    【解决方案1】:

    我想出了一个解决方案。

    我使用画笔过滤的 x.domain 过滤掉我的原始数据集。这个新过滤的数据集只有属于画笔的值:

    // Use x.domain to filter the data, then find the max and min duration of this new set, then set y.domain to that
      x.domain(brush.empty() ? x2.domain() : brush.extent());
      var dataFiltered = data.filter(function(d, i) {
        if ( (d.date >= x.domain()[0]) && (d.date <= x.domain()[1]) ) {
          return d.duration;
        }
      })
      y.domain([0, d3.max(dataFiltered.map(function(d) { return d.duration; }))]);
    

    最后,一定要重绘y轴和x轴:

    focus.select("path").attr("d", area);
    focus.select(".x.axis").call(xAxis);
    focus.select(".y.axis").call(yAxis);
    

    【讨论】:

    • 完美答案!能够直接进入我的图表代码,干杯。
    【解决方案2】:

    更短的可能性是在您的brush.extent() 上使用d3.scale.invert(),如下所示:

    var domainExtent = brush.extent().map(function(d){return scale.invert(d);});
    var filteredData = data.filter(function(d){return ((d <= domainExtent[1]) && (d >= domainExtent[0]));});
    

    不过,目前d3已经获得d3.brushX(),设计上只允许东西方向刷。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多