2

I have a D3 bar chart with date/time on the X axis. This is working well now, but I'd like to add a smaller brushable chart below it and am having trouble due to some of the date manipulations I had to do to make the bars center over the X axis tick lines - see this post for details on that.

The brush does not seem to be calculating the X axis date range correctly.

Here is the x domain definition and brush function. JSFiddle for the full code.

main_x.domain([
    d3.min(data.result, function(d) { return d.date.setDate(d.date.getDate() - 1); }),                  
    d3.max(data.result, function(d) { return d.date.setDate(d.date.getDate() + 2); })
]);

function brushed() {

    // I thought that re-defining the x domain without the date manipulations might work, but I 
    // was getting some odd results
    //main_x.domain(d3.extent(data.result, function(d) { return d.date; }));

    main_x.domain(brush.empty() ? main_x.domain() : brush.extent());
    console.log(brush.extent());

    bar.selectAll("rect")
        .attr("width", function(d) { return main_width/len; })
        .attr("x", function(d) { return main_x(d.date) - (main_width/len)/2; });

    main.select(".x.axis").call(main_xAxis);
}
Community
  • 1
  • 1
JamesE
  • 3,833
  • 9
  • 44
  • 82

1 Answers1

2

The problem is that you're using the same scale for the focus and the context chart. As soon as you change that, the range of the selection changes (same size, but different underlying scale). To fix, use two different scales.

I've done this here, introducing mini_x as the x scale for the context chart.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Hi, In your fiddle, the bars are overlapping the y-axis. Do you have any idea, how I can push those moving bars behind y-axis as they move? Has it got anything to do with z-index or width? This is a very late comment, but would highly appreciate if you can help. Thanks. – Thomas Sebastian Feb 03 '16 at 05:01
  • There's no z-index in SVG; the elements are rendered in the order in which they appear in the DOM. You can rearrange them, see e.g. https://stackoverflow.com/questions/14167863/how-can-i-bring-a-circle-to-the-front-with-d3 You can also use a clip path to hide the parts outside the chart area http://bl.ocks.org/mbostock/1667367 – Lars Kotthoff Feb 03 '16 at 05:11