Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - How to Add Legend To D3 Pie Chart

I have been trying to add a legend to this pie chart that I have created. I tried using code from getting a legend using a bar chart but I do not think it works or translates when trying to use it for a pie graph like this one I have. Is there a way to add a legend to this pie chart that I have made?

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Pie Chart</title>

  <!-- Bootstrap core CSS -->
  <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <!-- Custom styles for this template -->
  <link href="css/modern-business.css" rel="stylesheet">

  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>

</head>

<body>
  <script>

var data = [{test: "Negative At-Home", value: "1800"},
                    {test: "Positive At-Home", value: "600"},
                    {test: "Negative Mobile Tests", value: "500"},
                    {test: "Positive Mobile Tests", value: "300"}]
        
        // Selecting SVG using d3.select() 
        var svg = d3.select("svg"); 
            
        // Creating Pie generator 
        var pie = d3.pie(); 

        // Creating arc 
        var arc = d3.arc() 
                    .innerRadius(0) 
                    .outerRadius(100); 

        let g = svg.append("g") 
                    .attr("transform", "translate(150,120)"); 

        // Grouping different arcs 
        var arcs = g.selectAll("arc") 
                    .data(pie(data.value)) 
                    .enter() 
                    .append("g"); 

        // Appending path  
        arcs.append("path") 
            .attr("fill", (data, i)=>{ 
                let value=data.data; 
                return d3.schemeSet3[i+1]; 
            }) 
            .attr("d", arc); 
     
                

    </script>
</body>
</html>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...