简体   繁体   中英

unresponsive bars in otherwise responsive grouped d3 bar chart

I am trying to build a responsive grouped d3 bar chart using this as a guide:

http://blog.webkid.io/responsive-chart-usability-d3/

I have also used this for guidance on creating the grouped chart:

https://bl.ocks.org/mbostock/3887051

I now have a chart that resizes the axis and gridlines on window resize, but the bars (rects) remain fixed. Based on the code from mbostock's example, it's unclear to me what needs to change to allow the bars to move to their new positions as the x axis resizes.

Code samples below from the 3 key methods. init gets run and calls render on first load. Then the event listener for window resize runs render .

code from init method:

x = d3.scale.ordinal().domain(data.map(d => d.label));
x1 = d3.scale.ordinal().domain(scales);
y = d3.scale.linear().domain([0, 5]);

xAxis = d3.svg.axis().orient('bottom');
yAxis = d3.svg.axis()
  .orient('left')

svg = d3.select(element).append('svg');
chartWrapper = svg.append('g');
chartWrapper.append('g').classed('x axis', true);
chartWrapper.append('g').classed('y axis', true);

code from render method:

x.rangeBands([0, width]);
x1.rangeRoundBands([0, x.rangeBand()]);
y.range([height, 0]);

svg
  .attr('width', width + margin.right + margin.left)
  .attr('height', height + margin.top + margin.bottom);
chartWrapper.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');

xAxis.scale(x);
yAxis.scale(y);

svg.select('.x.axis')
  .attr('transform', 'translate(0, ' + height + ')')
  .call(xAxis)

svg.select('.y.axis')
  .call(yAxis)

bars = svg.selectAll('.bar')
  .data(data)
.enter().append("g")
  .attr("class", "bar")
  .attr("transform", d => "translate(" + x(d.label) + ", 0)");

bars.selectAll("rect")
  .data(d => d.scores)
  .enter()
    .append("rect")
    .attr("transform", "translate(125, 21)")
    .attr("width", x1.rangeBand())
    .attr("x", d => x1(d.name))
    .attr("y", d => y(d.value))
    .attr("height", d => height - y(d.value))

code from updateDimensions:

margin.top = 20;
margin.right = 10;
margin.left = 125;
margin.bottom = 110;

width = elementWidth - margin.left - margin.right;
height = 500 - margin.top - margin.bottom;

I'll also add that I've looked into some of the other solutions for responsive charts, such as using the viewBox to resize the entire svg. I prefer the approach of using a window resize event handler so I can make modifications to the chart for smaller devices.

Any assistance is much appreciated.

well, I have found a solution. Dunno if it's a good one, but it gets the job done!

adding svg.selectAll('.bar').remove(); prior to adding the bar elements was the trick.

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