alexc
alexc

Reputation: 1310

Adjusting rectangle size according to updated data (d3,js)

I made a similar post yesterday but after a few comments decided to delete it as I was very misguided about what my problem actually was, so I have worked on it and hopefully will be able to explain it more accurately.

I would like to update the size of 3 rectangles with new data but keep it relative to the parent width, rather than adjusting their size as a direct result from the data change.

Here is a plnk below;

http://plnkr.co/edit/eVfgniBQLbJLiMvAtWLI

This example shows how I would like the data to change. The issue here is that the width of the axis will expand/contract independent of the parent width.

I thought a solution could be this;

  // OLD SOLUTION
      x: d.y,
      y: d.x,
      x0: d.y0

  // NEW SOLUTION
      x: (d.y / calcTotal) * width,
      y: d.x,
      x0: (d.y0 / calcTotal) * width

This calculates the percentage of each number compared to the total amount of the new dataset, then times each number by the width of the parent container to ensure that each rectangle will change there size each time, but keep it relative to the parent width.

However, I'm not sure how to fix the rest of the functionality from here, as the rectangles don't change their size visually when the data is updated with my new solution?

I appreciate any advice!

Thanks

Upvotes: 3

Views: 1366

Answers (2)

Cyril Cherian
Cyril Cherian

Reputation: 32327

The problem is you are setting the data in the rectangle ONLY in the create block.

You should be updating the data in the rect and group like below:

//update the group with new data
groups = svg.selectAll('g')
  .data(dataset)


if (create) {
  groups
    .enter()
    .append('g').attr('class', 'stacked')
    .style('fill', function(d, i) {
      return colours(i);
    })
  rects = groups.selectAll('.stackedBar')
    .data(function(d, i) {
      return d;
    })

  rects
    .enter()
    .append('rect').attr('class', 'stackedBar')
    .attr('x', function(d) {
      return xScale(d.x0);
    })

  .attr('height', height)
    .attr('width', 0);
} else {
  .//update the rectangle with new data
  rects = groups.selectAll('.stackedBar')
    .data(function(d, i) {
      return d;
    })
}
//now do transition.

working code here

Upvotes: 2

chennighan
chennighan

Reputation: 476

I might have missed something, but what if you just change width=400 to width='100%' in your script.js? Here's my update: http://plnkr.co/edit/DKZdjposoN2omC55rM2d?p=preview

Then, when you change the data in your data.JSON it will reflect the width based on percentage of the parent container like you want.

Upvotes: 1

Related Questions