zoom in on a particular area in a line chart (using d3 and svelte)

Viewed 222

I am trying to zoom in on parts of a line chart using viewBox. I managed to get it working, however, not sure how to deal with the fact that everything scales accordingly (line path also becomes larger).

What I am looking for is for the line to stay constant while zoom is happening. I researched that there is also a way with translation and scale, but not sure how to implement it.

Also, not sure how to make this behavior more automatic. For example, I am zooming in on a range between two years: 2010 and 2011. Currently, I specify the y value manually. But ideally, this would be specified in using yScale function.

Any help would be appriciated!

Here is my repl: https://svelte.dev/repl/be0df7e353334108b3d432d5c82a6cd3?version=3.38.2

1 Answers

One way to accomplish this is by scaling the viewBox of the <svg> element.

You can do this by binding the x, y, width and height of the viewBox.

<svg ... viewBox="{x} {y} {width} {height}">

You can also tween the viewbox changes:

  1. By using Svelte's tweened() store for x, y, width, height. ie <svg viewBox="{$x} {$y} {$width} {$height}">
  2. Or by using SVG's <animate> element. ie <animate attributeName="viewBox" values="..." dur="2s"/>
Related