简体   繁体   中英

Updating x axis d3js

I'm trying to update my x axis in a D3js bar chart (is partially working) depending on a user filter, the bars are actually changing but is not doing it well. I don't really know where is the problem and I need some help.

in this part of the code I'm updating the bar chart

 function update(selectedGroup) {
    svg.selectAll("rect").remove()

    var groups = d3.map(dataFilter, function(d){return(d.group)}).keys();

    x.domain(groups);
    var dataFilter = result.filter(function(d){return d.group==selectedGroup});
    console.log(dataFilter);
    var rectG=rectangulos(dataFilter)

}

the complete bar chart全条形图

how is working now: the result should be something like this在此处输入图像描述

I have an live example here

There is a relatively straightforward reason you are seeing this behavior.

When the domain of the scale x is all the groups x.bandwidth() is small. But when the domain of x is only one value, x.bandwidth() is large. In both cases, the first band starts in the same location.

Next we have a nested scale here xSubgroup - the range of this is equal to x.bandwidth() . When the domain of x changes, we need to update the range of xSubgroup . If we don't do this, the bars will still be very thin and start at the beginning of the axis (as the bars' bandwidth aren't changing even if the group's bandwidth does). You don't update the sub scale's range, but we need to do that:

 x.domain(groups);
 xSubgroup.range([0, x.bandwidth()])

With this we get the update we're looking for.

But the axis labels remain unchanged. Updating a scale doesn't update the axis unless we explicitly do so. I'll break up your method chaining and store a reference for the g holding the axis:

var xAxis = svg.append("g")    
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

xAxis.selectAll("text")
  ...

Now we can update the axis, I'm carrying forward the text styling as well. You can simplify the code by using an update function to do all the entering/exiting/updating of axes and data - here we have some duplication in that both the initial set up and the update function have overlap.

To update the axis we use:

 // Call the axis again to update
 xAxis.call(d3.axisBottom(x))
 xAxis.selectAll("text")
  .style("text-anchor", "end")
  .attr("font-size", "55px")
  .attr("y", "-7")
  .attr("x", "-7")
  .attr("transform", "rotate(-90)");

Which gives the desired behavior if I understand correctly, updated plunkr

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