Vega-lite in svelte
There are many ways of incorporating graphics and plots in svelte and svelte-kit applications. I can definitely recommend checking out this talk by Matthias Stahl, graphics lead at Der Spiegel in Germany. This talk goes specifically through creating animated plots in svelte at the 24:46 mark.
So you can code your own SVG in svelte, use D3, P5, Three.js, etc. In the code below, we use vega-lite.
What I wanted to achieve with this component, is that the user can choose which dimensions are plotted against each other in a scatterplot. It was a bit tricky to get that interactivity working, which is the reason I’m writing it down here.
Our starting point
This is the basic plot we want to recreate in svelte, with the added functionality of allowing the user to select the axes.
|
|
This creates the following plot:
The svelte version
In the code below, I have removed the data from the spec itself just because most of my components read their data from an API endpoint. That’s what the <script context="module">
does at the top. So you can skip that part if you want.
|
|
On lines 25 to 33, we create a spec from which we removed all parts that are dynamic: the data, the width and height, and the fields used for the axes. These are added in the following lines 34 through 40. That code block is executed whenever one of its variables changes value.
The vega spec is mounted on the div called vis
on line 42.
We create two drop-down lists for selecting fieldX
and fieldY
, looping over all properties and changing the value of these variables.
The result:
That’s it.