JSFiddle - React, Tailwind, and code Playground

by anoopsuda

HTML

<script src="https://d3js.org/d3.v7.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>D3 Pie Chart with Hover Effects</title>
    
    <style>
        .tooltip {
            position: absolute;
            text-align: center;
            width: 100px;
            height: auto;
            padding: 8px;
            font: 12px sans-serif;
            background: lightsteelblue;
            border: 0px;
            border-radius: 8px;
            pointer-events: none;
            opacity: 0;
        }
    </style>
</head>
<body>
 <div id="chart"></div>
 </body>
 </html>

JavaScript

// Dummy data
        const data = [
            {label: "A", value: 30},
            {label: "B", value: 70},
            {label: "C", value: 45},
            {label: "D", value: 65},
            {label: "E", value: 20}
        ];

        // Set dimensions and radius
        const width = 400, height = 400, radius = Math.min(width, height) / 2;

        // Create color scale
        const color = d3.scaleOrdinal()
            .domain(data.map(d => d.label))
            .range(d3.schemeCategory10);

        // Create SVG container
        const svg = d3.select("#chart").append("svg")
            .attr("width", width)
            .attr("height", height)
            .append("g")
            .attr("transform", `translate(${width / 2}, ${height / 2})`);

        // Tooltip
        const tooltip = d3.select("body").append("div")
            .attr("class", "tooltip");

        // Define arc generator
        const arc = d3.arc()
            .innerRadius(0)
            .outerRadius(radius - 20);

        // Define arc for hover effect
        const arcHover = d3.arc()
            .innerRadius(0)
            .outerRadius(radius - 10);

        // Create pie generator
        const pie = d3.pie()
            .value(d => d.value)
            .sort(null);

        // Draw arcs
        const arcs = svg.selectAll(".arc")
            .data(pie(data))
            .enter()
            .append("g")
            .attr("class", "arc");

        // Append paths, set colors and add hover effects
        arcs.append("path")
            .attr("d", arc)
            .attr("fill", d => color(d.data.label))
            .on("mouseover", function(event, d) {
                d3.select(this)
                    .transition()
                    .duration(200)
                    .attr("d", arcHover)  // Increase size slightly
                    .style("fill", "#BE82FF");  // Change color on hover

                tooltip.transition().duration(200).style("opacity", 0.9);
               ...