Back to articles

Building Interactive Data Visualizations with Svelte and D3.js

AuthorMajd Muhtaseb05/14/202510 minutes
Building Interactive Data Visualizations with Svelte and D3.js

Introduction

Svelte and D3.js are a powerful combination for creating interactive data visualizations. Svelte provides a component-based approach for building user interfaces, while D3.js offers a comprehensive set of tools for manipulating the DOM and creating dynamic graphics. This article demonstrates how to integrate these two technologies to create compelling visualizations.

Setting Up Your Project

First, create a new Svelte project:

npx degit sveltejs/template my-svelte-d3-app
cd my-svelte-d3-app
npm install
npm install d3

Creating a Simple Bar Chart

Let's create a basic bar chart using D3.js within a Svelte component.

src/lib/BarChart.svelte:

<script>
  import * as d3 from 'd3';
  import { onMount } from 'svelte';

  export let data;
  export let width = 600;
  export let height = 400;
  export let margin = { top: 20, right: 30, bottom: 40, left: 50 };

  let svg;

  onMount(() => {
    const innerWidth = width - margin.left - margin.right;
    const innerHeight = height - margin.top - margin.bottom;

    const xScale = d3.scaleBand()
      .domain(data.map(d => d.label))
      .range([0, innerWidth])
      .padding(0.1);

    const yScale = d3.scaleLinear()
      .domain([0, d3.max(data, d => d.value)])
      .range([innerHeight, 0]);

    const g = d3.select(svg)
      .attr('width', width)
      .attr('height', height)
      .append('g')
      .attr('transform', `translate(${margin.left},${margin.top})`);

    g.selectAll('.bar')
      .data(data)
      .enter()
      .append('rect')
      .attr('class', 'bar')
      .attr('x', d => xScale(d.label))
      .attr('y', d => yScale(d.value))
      .attr('width', xScale.bandwidth())
      .attr('height', d => innerHeight - yScale(d.value))
      .attr('fill', 'steelblue');

    g.append('g')
      .attr('transform', `translate(0,${innerHeight})`)
      .call(d3.axisBottom(xScale));

    g.append('g')
      .call(d3.axisLeft(yScale));
  });
</script>

<svg bind:this={svg}></svg>

<style>
  .bar {
    stroke: none;
  }
</style>

src/routes/+page.svelte:

<script>
  import BarChart from '$lib/BarChart.svelte';

  const data = [
    { label: 'A', value: 20 },
    { label: 'B', value: 35 },
    { label: 'C', value: 30 },
    { label: 'D', value: 45 },
    { label: 'E', value: 10 }
  ];
</script>

<BarChart {data} />

Explanation

  1. Import necessary libraries: We import d3 and onMount from Svelte.
  2. Define props: The data, width, height, and margin props allow customization of the chart.
  3. onMount lifecycle: The onMount function ensures that the D3.js code runs after the component is mounted to the DOM.
  4. Scales: We define xScale and yScale to map data values to pixel positions.
  5. SVG element: We create an SVG element and append a group (g) to it for the chart.
  6. Bars: We create bars using selectAll, data, enter, and append.
  7. Axes: We add x and y axes using d3.axisBottom and d3.axisLeft.

Adding Interactivity

You can add interactivity by using Svelte's event handling capabilities. For example, you can add a tooltip to display the value of each bar on hover.

Conclusion

This article provides a basic introduction to creating data visualizations with Svelte and D3.js. You can extend this example to create more complex and interactive visualizations by exploring D3.js's extensive API and Svelte's reactive features.