gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:13:46 26 4
gpt4 key购买 nike

使用 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/

26 4 0