简体   繁体   中英

D3.js bar chart 'enter' appears to draw the new bars in wrong position

I have been following several tutorials / articles on D3.js to create a bar chart with drill-through type functionality. I have it working pretty much how I want it but have a problem that I just can't seem to figure out.

I have an example that I am working on here (this is cut down version from the main one I'm working on, just to show the issue): http://jsfiddle.net/MattFrewin/bobec00k/1/

You can see that the initial bar chart shows 1 bar for 'Team A', you can click on this to drill through to the next set of data - which shows 3 bars of data. The problem is that the new bars are all slightly out of place. You will notice that I am using a margin for the chart axis which offsets the bars, and from what I can tell it is this that is not being taken into account on the new bars. Here is the bit of code which I think is where the issues is:

//Create bars
chartBarData.enter()
  .append("rect")
    .attr({
        "x": function (d) { return xScale(d.key); },
        "y": height,
        "width": xScale.rangeBand(),
        "height": 0,
        "fill": function (d) { return "rgb(0, 130, 0)"; }
    })
    .transition().delay(animDur).duration(animDur)
    .attr({
        "x": function (d) { return xScale(d.key); },
        "y": function (d) { return yScale(d.values.count); },
        "width": xScale.rangeBand(),
        "height": function (d) { return height - yScale(d.values.count); },
        "fill": function (d) { return "rgb(0, 130, 0)"; }
    });

I have found a way around it by putting the margins into the 'x' and 'y' parts of the 'rect' attributes but this causes further similar issues when drilling further down into the data. I'm sure there is something obvious I am missing or probably just do not quite understand D3 fully yet! Any help is appreciated.

EDIT: I should also add that the D3 'update' section appears to work fine, using the same scales as the 'enter' section - which is confusing! As you will see on the jsfiddle link, the first bar is lined up correctly when you drill through but the other two are not.

It seems bars are not inserted into the proper location, in chart_drilldown function try to replace:

var chartBarData = theChart.selectAll("rect")
        .data(groupedData);

with

var chartBarData = theChart.select("g").selectAll("rect")
        .data(groupedData);

Modified JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM