Imagine: you have 50,000 transactions, need to show trends and anomalies in real time, but ready-made libraries only provide a line chart and a couple of tooltips. The client needs a custom dashboard with synchronized zoom, time range filtering, and PNG export. Standard solutions are powerless here — you need D3.js.
D3.js (Data-Driven Documents) is a JavaScript library for data visualization using web standards. It's not a chart library, but a tool for binding data to the DOM and managing SVG, Canvas, and HTML. Most ready-made libraries (Chart.js, Recharts, Highcharts) are built on top of D3 or use similar ideas, but offer fixed chart types. D3 is a level below: when you need to visualize something non-standard or get full control over interactivity for interactive dashboards and analytical dashboards. Our experience — over 5 years in data visualization and 50+ completed projects, including custom charts and responsive dashboards. We guarantee quality and adherence to deadlines. Learn more about D3.js on Wikipedia.
Why D3.js is Better than Ready-Made Libraries for Complex Dashboards?
Recharts or Chart.js are the right choice for standard tasks: a linear trend, bar chart, pie. Install, three props, done. D3 is justified when:
- Custom projection is needed (maps, radar charts with non-linear axes)
- Interactivity requires precise state management (brush selection, zoom with synchronization)
- Animations must be data-driven via transitions
- Multiple linked visualizations with shared state (brushing & linking)
| Criterion | D3.js | Ready-Made Library |
|---|---|---|
| Visualization type | Any (maps, Sankey, Chord) | Standard (line, bar, pie) |
| Style control | Full | Limited API |
| Interactivity | Arbitrary (zoom, brush, drag) | Only built-in |
| Performance | Manual optimization (Canvas, WebGL) | Automatic (often low for >1k points) |
| Learning curve | High | Low |
D3.js provides 3 times more flexibility compared to ready-made chart libraries, allowing unique visualizations without compromises. Using D3.js reduces licensing costs for third-party libraries, and high-quality visualization pays off by improving data analysis efficiency.
Integrating D3.js with React
We use a hybrid approach: D3 for calculations and complex interactions, React for state management and container rendering. Here's the basic pattern we apply in 90% of projects:
import { useEffect, useRef } from 'react';
import * as d3 from 'd3';
interface LineChartProps {
data: { date: Date; value: number }[];
width?: number;
height?: number;
}
export function LineChart({ data, width = 800, height = 400 }: LineChartProps) {
const svgRef = useRef<SVGSVGElement>(null);
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
useEffect(() => {
if (!svgRef.current || !data.length) return;
const svg = d3.select(svgRef.current);
svg.selectAll('*').remove();
const g = svg
.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
const xScale = d3
.scaleTime()
.domain(d3.extent(data, d => d.date) as [Date, Date])
.range([0, innerWidth]);
const yScale = d3
.scaleLinear()
.domain([0, d3.max(data, d => d.value) ?? 0])
.nice()
.range([innerHeight, 0]);
const line = d3
.line<{ date: Date; value: number }>()
.x(d => xScale(d.date))
.y(d => yScale(d.value))
.curve(d3.curveMonotoneX);
g.append('g')
.attr('transform', `translate(0,${innerHeight})`)
.call(d3.axisBottom(xScale).ticks(6).tickFormat(d3.timeFormat('%d %b')));
g.append('g').call(
d3.axisLeft(yScale).ticks(5).tickFormat(d => d3.format(',.0f')(+d))
);
g.append('path')
.datum(data)
.attr('fill', 'none')
.attr('stroke', '#3b82f6')
.attr('stroke-width', 2)
.attr('d', line);
const tooltip = d3.select('#tooltip');
g.selectAll('.dot')
.data(data)
.join('circle')
.attr('class', 'dot')
.attr('cx', d => xScale(d.date))
.attr('cy', d => yScale(d.value))
.attr('r', 4)
.attr('fill', '#3b82f6')
.on('mouseover', (event, d) => {
tooltip
.style('display', 'block')
.style('left', `${event.pageX + 12}px`)
.style('top', `${event.pageY - 28}px`)
.html(`<strong>${d3.timeFormat('%d %b %Y')(d.date)}</strong><br/>${d3.format(',.0f')(d.value)}`);
})
.on('mouseout', () => {
tooltip.style('display', 'none');
});
}, [data, width, height]);
return (
<>
<svg ref={svgRef} width={width} height={height} />
<div
id="tooltip"
style={{
position: 'absolute',
display: 'none',
background: 'rgba(0,0,0,0.75)',
color: '#fff',
padding: '6px 10px',
borderRadius: 4,
fontSize: 12,
pointerEvents: 'none',
}}
/>
</>
);
}
The second option is React rendering SVG, D3 only calculates scale and path. It's easier to test but more complex with animations. The choice depends on the task.
D3 Interactive Features
D3 zoom, D3 brush, tooltip, drag, sorting, filtering, synchronization of multiple charts (brushing & linking). D3 allows precise state and event management, important for analytical dashboards.
How to Synchronize Multiple Charts?
The classic pattern is brushing & linking: selecting a range on one chart filters data on all others.
function Dashboard() {
const [brushRange, setBrushRange] = useState<[Date, Date] | null>(null);
const filteredData = useMemo(() => {
if (!brushRange) return fullData;
return fullData.filter(d => d.date >= brushRange[0] && d.date <= brushRange[1]);
}, [brushRange]);
return (
<div className="grid grid-cols-2 gap-4">
<TimelineChart data={fullData} onBrush={setBrushRange} />
<BarChart data={filteredData} />
<ScatterPlot data={filteredData} />
<MetricsTable data={filteredData} />
</div>
);
}
Performance Optimization with Large Data Sets
D3 + SVG starts to lag after ~5000 points. Solutions: Canvas for scatter plots (managed via canvas.getContext('2d')) or decimation (LTTB).
| Technology | Performance | Implementation Complexity |
|---|---|---|
| SVG | Up to 5000 points | Low |
| Canvas | Up to 100,000 points | Medium |
| WebGL | Up to 1 million points | High |
LTTB Algorithm (code)
```typescript function lttbDecimate(data: Point[], threshold: number): Point[] { if (data.length <= threshold) return data;const sampled: Point[] = [data[0]]; const bucketSize = (data.length - 2) / (threshold - 2);
for (let i = 0; i < threshold - 2; i++) { const rangeStart = Math.floor((i + 1) * bucketSize) + 1; const rangeEnd = Math.min(Math.floor((i + 2) * bucketSize) + 1, data.length); // ... calculation of triangle area let maxArea = -1; let maxPoint = data[rangeStart]; for (let j = rangeStart; j < rangeEnd; j++) { const area = Math.abs( (sampled[sampled.length - 1].x - avgX) * (data[j].y - sampled[sampled.length - 1].y) - (sampled[sampled.length - 1].x - data[j].x) * (avgY - sampled[sampled.length - 1].y) ); if (area > maxArea) { maxArea = area; maxPoint = data[j]; } } sampled.push(maxPoint); } sampled.push(data[data.length - 1]); return sampled; }
</details>
### Export SVG to PNG/PDF
```typescript
async function exportChart(svgElement: SVGSVGElement, filename: string) {
const serializer = new XMLSerializer();
const svgStr = serializer.serializeToString(svgElement);
const blob = new Blob([svgStr], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = svgElement.viewBox.baseVal.width * 2;
canvas.height = svgElement.viewBox.baseVal.height * 2;
const ctx = canvas.getContext('2d')!;
ctx.scale(2, 2);
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(url);
canvas.toBlob(blob => {
const a = document.createElement('a');
a.href = URL.createObjectURL(blob!);
a.download = `${filename}.png`;
a.click();
});
};
img.src = url;
}
Work Process
- Analytics — study data, agree on visualization types, prototype on paper.
- Design — choose stack (D3 + React/Vue, Canvas/SVG), design interactions.
- Implementation — write code, configure responsiveness, optimize performance.
- Testing — test on real data, fix bugs.
- Deployment — deploy on your server or in the cloud, hand over access.
What's Included
- Source code with comments and documentation
- Mobile responsiveness setup
- Team training (1-2 sessions)
- Warranty support for 2 weeks after delivery
- Integration with your CMS or API (Laravel, Node.js)
Timeline and Cost
- Single custom chart with interactivity (tooltip, zoom) — from 2 to 4 days.
- Analytical dashboard with 4-6 interconnected visualizations — from 3 to 5 weeks.
- Complex geovisualizations — individual assessment after data review.
Cost is calculated individually. Budget savings due to no licensing fees for commercial libraries. For example, a single interactive chart starts at $1,000, and a full dashboard with 4-6 interconnected visualizations ranges from $8,000 to $15,000. For an accurate estimate, send sample data and requirements — we'll provide a commercial proposal within 2 business days. Contact us for a consultation on your project. Order custom dashboard development — we'll evaluate your project and offer the optimal solution. If you need a non-standard visualization — get a consultation on your project.







