D3.js Basic Pie Chart with Legend

遇到一個參考性佳的pie chart with legend 的範例:
https://observablehq.com/@sengokyu/d3-js-basic-pie-chart-with-legend

{
  const svg = d3
    .create('svg')
    .attr('width', width)
    .attr('height', height);
  const chart = svg
    .append('g')
    .attr('transform', `translate(${radius},${radius})`);

  chart
    .selectAll(null)
    .data(pieData)
    .enter()
    .append('path')
    .attr('d', arc)
    .attr('fill', d => colorSeq(d.index))
    .attr('stroke', 'grey')
    .style('stroke-width', '1px');

  const legend = svg
    .append('g')
    .attr('transform', `translate(${radius * 2 + 20},0)`);

  legend
    .selectAll(null)
    .data(pieData)
    .enter()
    .append('rect')
    .attr('y', d => labelHeight * d.index * 1.8)
    .attr('width', labelHeight)
    .attr('height', labelHeight)
    .attr('fill', d => colorSeq(d.index))
    .attr('stroke', 'grey')
    .style('stroke-width', '1px');

  legend
    .selectAll(null)
    .data(pieData)
    .enter()
    .append('text')
    .text(d => d.data.key)
    .attr('x', labelHeight * 1.2)
    .attr('y', d => labelHeight * d.index * 1.8 + labelHeight)
    .style('font-family', 'sans-serif')
    .style('font-size', `${labelHeight}px`);

  return svg.node();
}

常數們:

labelHeight = 18
radius = 150
height = 300
width = 600

相關文章

Building legends in d3.js
https://d3-graph-gallery.com/graph/custom_legend.html

Color legend
https://observablehq.com/@d3/color-legend

d3js Legends
https://observablehq.com/plot/features/legends#legend-options

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *