Building Interactive Data Visualizations with Svelte and D3.js
Introduction
Svelte and D3.js make a powerful combination for building interactive and dynamic data visualizations. Svelte's component-based architecture and reactivity simplify managing the DOM, while D3.js provides the tools necessary for complex chart creation. This article will guide you through creating a basic bar chart with interactive features.
Setting Up Your Svelte Project
First, ensure you have a Svelte project set up. If not, create one using:
npx degit sveltejs/template my-svelte-d3-project
cd my-svelte-d3-project
npm install
npm install d3
npm run dev
Creating the Bar Chart Component
Create a new Svelte component, BarChart.svelte
:
<script>
import { onMount } from 'svelte';
import * as d3 from 'd3';
export let data;
export let width = 600;
export let height = 400;
export let margin = { top: 20, right: 30, bottom: 40, left: 40 };
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]);
svg = d3.select('#bar-chart')
.attr('width', width)
.attr('height', height);
const g = svg.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>
<style>
.bar {
transition: fill 0.3s ease;
}
.bar:hover {
fill: orange;
cursor: pointer;
}
</style>
<svg id="bar-chart"></svg>
Integrating the Component
In your App.svelte
, import and use the BarChart
component:
<script>
import BarChart from './BarChart.svelte';
const data = [
{ label: 'A', value: 20 },
{ label: 'B', value: 35 },
{ label: 'C', value: 30 },
{ label: 'D', value: 45 },
{ label: 'E', value: 25 }
];
</script>
<main>
<h1>Interactive Bar Chart</h1>
<BarChart {data} />
</main>
<style>
main {
text-align: center;
padding: 1em;
}
</style>
Explanation
- Import necessary libraries: Import
onMount
from Svelte andd3
from D3.js. - Data binding:
data
prop allows you to pass data to the component. - D3.js setup: Inside
onMount
, we use D3.js to create scales, axes, and bars. - Interactive Hover: CSS styles provide visual feedback on hover.
Conclusion
This example demonstrates the fundamental principles of using Svelte and D3.js for creating interactive data visualizations. You can further enhance this by adding more complex interactions, animations, and data sources.