how to get force graph to fit in viewport

Sorry if this question has been answered, but I’m struggling to size this force graph so that it fits in the viewport - I basically just want to scale it down. I tried increasing the width and height substantially, but it still gets cut off. I added this code, but it didn’t have an effect:

svg = d3.create("svg")
    .attr("viewBox", [-width/2, -height/2, width, height])
    .style('max-width', '100%')
    .style('height', 'auto');

Thanks in advance for your help!

hi @maxeneg , if you want it to scale down you might want to replace/override all width references with a static number. width inside Observable is a reactive variable, every time the viewport resize your force graph is regenerated with a new width value.

Thanks @radames! I had tried this too but it still went out of bounds - I did as much as 932.

Would you mind sharing a link to your notebook?

Yea no problem! Here it is. Thanks for taking a look at it.

@radames do you think the only option would be to pull it out of observable? Otherwise, I’ll just hack it and make the circles smaller.

I just tried this and it’s getting closer to fitting:

svg = d3.create("svg")
    .attr("viewBox", [-width/2, -height/2, width*2, height*2])
    .style('max-width', '80%')
    .style('height', 'auto');


1 Like

hi @maxeneg,

I see the issue now, after the simulation is done the nodes are spread around and I’m not sure how can you calculate the boundary beforehand. But you can readjust the viewport like @aaronkyle suggestion. You can calculate the nodes extent x and y after the simulation and readjust the viewport

    const xExtent = d3.extent(, d => d.x);
    const yExtent = d3.extent(, d => d.y);
    const newWidth = Math.abs(xExtent[0]) + xExtent[1];
    const newHeight = Math.abs(yExtent[0]) + yExtent[1];
    svg.attr("viewBox", [xExtent[0], yExtent[0], newWidth, newHeight]);
1 Like

Hey @radames! This is great! I wouldn’t have thought to do that. I really appreciate your help - I bet this logic will come in handy in subsequent projects.

1 Like