Create interactive, responsive data visualizations with D3.js and React integration in Google Antigravity
# D3.js Data Visualization for Google Antigravity
D3.js enables powerful, custom data visualizations. This guide covers D3.js patterns with React integration optimized for Google Antigravity IDE and Gemini 3.
## Responsive Chart Hook
```typescript
// hooks/useChartDimensions.ts
import { useState, useEffect, useRef, useCallback } from 'react';
interface Dimensions {
width: number;
height: number;
marginTop: number;
marginRight: number;
marginBottom: number;
marginLeft: number;
boundedWidth: number;
boundedHeight: number;
}
const defaultMargins = {
marginTop: 40,
marginRight: 30,
marginBottom: 40,
marginLeft: 60,
};
export function useChartDimensions(customMargins?: Partial<typeof defaultMargins>) {
const ref = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState<Dimensions>({
width: 0,
height: 0,
...defaultMargins,
...customMargins,
boundedWidth: 0,
boundedHeight: 0,
});
const updateDimensions = useCallback(() => {
if (!ref.current) return;
const { width, height } = ref.current.getBoundingClientRect();
const margins = { ...defaultMargins, ...customMargins };
setDimensions({
width,
height,
...margins,
boundedWidth: Math.max(width - margins.marginLeft - margins.marginRight, 0),
boundedHeight: Math.max(height - margins.marginTop - margins.marginBottom, 0),
});
}, [customMargins]);
useEffect(() => {
updateDimensions();
const observer = new ResizeObserver(updateDimensions);
if (ref.current) observer.observe(ref.current);
return () => observer.disconnect();
}, [updateDimensions]);
return { ref, dimensions };
}
```
## Reusable Line Chart Component
```typescript
// components/LineChart.tsx
import { useRef, useEffect, useMemo } from 'react';
import * as d3 from 'd3';
import { useChartDimensions } from '../hooks/useChartDimensions';
interface DataPoint {
date: Date;
value: number;
}
interface LineChartProps {
data: DataPoint[];
xLabel?: string;
yLabel?: string;
color?: string;
showGrid?: boolean;
animate?: boolean;
}
export function LineChart({
data,
xLabel = '',
yLabel = '',
color = '#3b82f6',
showGrid = true,
animate = true,
}: LineChartProps) {
const { ref, dimensions } = useChartDimensions();
const svgRef = useRef<SVGSVGElement>(null);
// Memoize scales
const scales = useMemo(() => {
if (!dimensions.boundedWidth || !dimensions.boundedHeight) return null;
const xScale = d3.scaleTime()
.domain(d3.extent(data, d => d.date) as [Date, Date])
.range([0, dimensions.boundedWidth]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value) || 0])
.range([dimensions.boundedHeight, 0])
.nice();
return { xScale, yScale };
}, [data, dimensions]);
useEffect(() => {
if (!svgRef.current || !scales) return;
const svg = d3.select(svgRef.current);
const { xScale, yScale } = scales;
const { marginLeft, marginTop, boundedWidth, boundedHeight } = dimensions;
// Clear previous content
svg.selectAll('*').remove();
// Create main group
const g = svg.append('g')
.attr('transform', `translate(${marginLeft},${marginTop})`);
// Add grid lines
if (showGrid) {
g.append('g')
.attr('class', 'grid')
.attr('opacity', 0.1)
.call(d3.axisLeft(yScale)
.tickSize(-boundedWidth)
.tickFormat(() => '')
);
}
// Add axes
g.append('g')
.attr('class', 'x-axis')
.attr('transform', `translate(0,${boundedHeight})`)
.call(d3.axisBottom(xScale).ticks(6));
g.append('g')
.attr('class', 'y-axis')
.call(d3.axisLeft(yScale).ticks(5));
// Add axis labels
if (xLabel) {
g.append('text')
.attr('x', boundedWidth / 2)
.attr('y', boundedHeight + 35)
.attr('text-anchor', 'middle')
.attr('fill', 'currentColor')
.text(xLabel);
}
if (yLabel) {
g.append('text')
.attr('transform', 'rotate(-90)')
.attr('x', -boundedHeight / 2)
.attr('y', -45)
.attr('text-anchor', 'middle')
.attr('fill', 'currentColor')
.text(yLabel);
}
// Create line generator
const line = d3.line<DataPoint>()
.x(d => xScale(d.date))
.y(d => yScale(d.value))
.curve(d3.curveMonotoneX);
// Add line path
const path = g.append('path')
.datum(data)
.attr('fill', 'none')
.attr('stroke', color)
.attr('stroke-width', 2)
.attr('d', line);
// Animate line drawing
if (animate) {
const pathLength = path.node()?.getTotalLength() || 0;
path
.attr('stroke-dasharray', `${pathLength} ${pathLength}`)
.attr('stroke-dashoffset', pathLength)
.transition()
.duration(1500)
.ease(d3.easeQuadOut)
.attr('stroke-dashoffset', 0);
}
// Add interactive dots
const dots = 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', color)
.attr('opacity', 0);
// Add tooltip interaction
const tooltip = d3.select('body').append('div')
.attr('class', 'd3-tooltip')
.style('opacity', 0);
dots.on('mouseenter', function(event, d) {
d3.select(this).attr('opacity', 1).attr('r', 6);
tooltip.transition().duration(200).style('opacity', 1);
tooltip.html(`
<strong>${d3.timeFormat('%b %d, %Y')(d.date)}</strong><br/>
Value: ${d.value.toLocaleString()}
`)
.style('left', `${event.pageX + 10}px`)
.style('top', `${event.pageY - 10}px`);
})
.on('mouseleave', function() {
d3.select(this).attr('opacity', 0).attr('r', 4);
tooltip.transition().duration(200).style('opacity', 0);
});
return () => tooltip.remove();
}, [data, scales, dimensions, color, showGrid, animate, xLabel, yLabel]);
return (
<div ref={ref} className="w-full h-80">
<svg ref={svgRef} width={dimensions.width} height={dimensions.height} />
</div>
);
}
```
## Best Practices
1. **Separate Concerns**: Keep D3 calculations in useMemo, rendering in useEffect
2. **Responsive Design**: Use ResizeObserver for dynamic chart sizing
3. **Accessibility**: Add ARIA labels and keyboard navigation
4. **Performance**: Use enter/update/exit pattern for data updates
5. **Clean Transitions**: Interrupt ongoing transitions before starting new ones
6. **Mobile Touch**: Support touch events for tooltips on mobile devices
Google Antigravity's Gemini 3 excels at generating D3.js visualizations from data descriptions and can help optimize complex chart interactions.This D3.js prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their d3.js implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For D3.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.