Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
D3.js Data Visualization

D3.js Data Visualization

Create interactive, responsive data visualizations with D3.js and React integration in Google Antigravity

D3.jsData VisualizationChartsReactSVG
by Antigravity Team
⭐0Stars
👁️1Views
.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.

When to Use This Prompt

This D3.js prompt is ideal for developers working on:

  • D3.js applications requiring modern best practices and optimal performance
  • Projects that need production-ready D3.js code with proper error handling
  • Teams looking to standardize their d3.js development workflow
  • Developers wanting to learn industry-standard D3.js patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the D3.js code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this D3.js prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...