reactjs - 重新绘制饼图,里面有/值标签

标签 reactjs recharts

使用 recharts 库,我很想创建一个这样的圆环图:
https://apexcharts.com/javascript-chart-demos/pie-charts/simple-donut/

具体来说,值标签位于饼图段内。我在文档中找到的唯一示例使用自定义渲染标签,但我希望使用新的标签组件,这会更容易:
http://recharts.org/en-US/examples/PieChartWithCustomizedLabel

按照这个例子,这是我能得到的最接近的,但标签没有居中:
enter image description here

这是新的 Label 组件文档。我试过了:<Label position="inside />
这是 customLabelRendering 的代码:

const RADIAN = Math.PI / 180;
const renderCustomizedLabel = ({
  cx, cy, midAngle, innerRadius, outerRadius, percent, index,
}) => {
   const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
  const x = cx + radius * Math.cos(-midAngle * RADIAN);
  const y = cy + radius * Math.sin(-midAngle * RADIAN);

  return (
    <text x={x} y={y} fill="white" textAnchor={x > cx ? 'start' : 'end'} dominantBaseline="central">
      {`${(percent * 100).toFixed(0)}%`}
    </text>
  );
};

最佳答案

您可以对齐 <text />带有 textAnchor="middle" 的标签这将使它们在所有单元格的中心对齐。

像这样:

<text x={x} y={y} fill="white" textAnchor="middle" dominantBaseline="central">
  {`${(percent * 100).toFixed(0)}%`}
</text>

您的最终代码应如下所示:
const RADIAN = Math.PI / 180;
const renderCustomizedLabel = ({
  cx, cy, midAngle, innerRadius, outerRadius, percent, index,
}) => {
   const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
  const x = cx + radius * Math.cos(-midAngle * RADIAN);
  const y = cy + radius * Math.sin(-midAngle * RADIAN);

  return (
    <text x={x} y={y} fill="white" textAnchor="middle" dominantBaseline="central">
      {`${(percent * 100).toFixed(0)}%`}
    </text>
  );
}

以上适用于文本,但如果您需要在中心使用图像,请使用 <svg /><image /> .
return (
  <svg
    x={x - 12}
    y={y - 12}
    fill="#666"
    textAnchor={"middle"}
    dominantBaseline="central"
    width={24}
    height={24}
    viewBox="0 0 1024 1024"
  >
    <image
      href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png"
      height="100%"
      width="100%"
    />
  </svg>
);

enter image description here

关于reactjs - 重新绘制饼图,里面有/值标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55247126/

相关文章:

reactjs - 来自服务器的数据时图例重叠

javascript - 将动态输入表单中的数据存储到对象(React)

css - 如何改变Ant-Design 'Select'组件的样式?

reactjs - 无法在 Typescript : JSX Element type does not have any construct or call signatures 中编写高阶组件

javascript - 过滤器从 react 数组中删除一个元素

reactjs - 标签列表未显示在图表中?

javascript - 使用 React 内联样式设置第三方元素的样式

reactjs - Recharts 不适用于带有 typescript 的 React

javascript - 仅针对某些数据点重新绘制 LineChart 点

javascript - React Recharts 使用大量数据渲染阻塞