1

I am creating a waffle chart with d3.js and I want to make it responsive to screen size. The way I am doing is I have a fixed size for each rectangle and I don't know how to change the size in response to the screen size.

I have tried it with two js files. One is for the desktop screen size and the other one is for mobile. However, it doesn't work as they were detected for using the same variable even though they belong to the different file. Another issue is that if I were to select g and/or selectall .rect in the first files, the machine will recognize that I am selecting all g and .rect on the DOM.

const width = 900;
const height = 500;
const numRows = 6;

let svg = d3.select('#waffle')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g');

// A failed attempt to make the chart responsive
let aspect = width / height,
chart = d3.select('#waffle');

d3.select(window)
.on("resize", function () {
    var targetWidth = chart.node().getBoundingClientRect().width;
    chart.attr("width", targetWidth);
    chart.attr("height", targetWidth / aspect);
});

// load data
d3.csv('data/tracker.csv')
.then(data => {
    drawWaffle(data);
})

// render the chart
function drawWaffle(data) {

plots = svg.selectAll('.rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('width', 20)
    .attr('height', 20)
    .attr('x', (d, i) => {
        let rowIndex = Math.floor(i / numRows)
            return (rowIndex * 22)
    })
    .attr('y', (d, i) => {
        let colIndex = i % numRows
            return (colIndex * 22)
    })
    .attr('rx', (d, i) => {
        return "10px"
    })
    .style('fill', camp_color)
    .style('stroke', 'none')
    .attr('transform', `translate(55, 21)`);
}

It's okay on desktop screen size but it looks terrible on mobile because of the fixed size for the rectangles.

Marcus Campbell
  • 2,746
  • 4
  • 22
  • 36
longhui
  • 13
  • 5
  • you can set the `viewbox` parameter on the svg, it will scale the image compared to the actual screenspace available (set in width and height) – rioV8 Dec 21 '18 at 11:30
  • 1
    This question has been asked and answered probably 20 times on this site. Have you look at any of those answers. See [here](https://stackoverflow.com/questions/9400615/whats-the-best-way-to-make-a-d3-js-visualisation-layout-responsive) and [here](https://stackoverflow.com/questions/17626555/responsive-d3-chart) and [here](https://stackoverflow.com/questions/16265123/resize-svg-when-window-is-resized-in-d3-js/25978286#25978286). – Mark Dec 21 '18 at 16:39

0 Answers0