You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-google-charts饼图需显示数值而非百分比的技术求助

解决react-google-charts饼图显示具体数值的问题

要让PieChart显示具体数值而非默认的百分比,只需修改图表的options配置,同时优化数据处理逻辑避免状态更新异常:

1. 修改饼图配置项

在现有options中添加sliceText属性,设置为'value'即可让饼图切片上直接显示具体数值;若需要 tooltip 也显示数值,可额外配置tooltip属性:

const options = {
    is3D: true,
    // 让饼图切片显示具体数值
    sliceText: 'value',
    // 可选:自定义tooltip显示内容,比如同时显示标签和数值
    tooltip: {
        text: 'value' // 或 'both' 同时显示标签、数值和百分比
    }
};

2. 优化数据处理逻辑

你的useEffect中直接修改原数组再更新状态,可能导致React无法正确识别状态变化,建议创建新数组来处理数据:

useEffect(() => {
    if (!schedulePatientCount) return; // 先判断数据是否存在,避免报错
    // 创建新数组,初始值保留表头
    const newAnalysisPatientCount = [['', '']];
    schedulePatientCount.forEach((ap: any) => {
        if (ap?.count !== undefined && ap?.machine.label !== undefined && ap?.count !== 0) {
            newAnalysisPatientCount.push([ap.machine.label, ap.count]);
        }
    });
    setAnalysisCountPatient(newAnalysisPatientCount);
}, [schedulePatientCount]); // 依赖项改为实际用到的schedulePatientCount,而非无关变量

修改后的完整关键代码片段

// ...其他代码不变
const [analysisCountPatient, setAnalysisCountPatient] = useState<any[]>([['', '']])

useEffect(() => {
    if (!schedulePatientCount) return;
    const newAnalysisPatientCount = [['', '']];
    schedulePatientCount.forEach((ap: any) => {
        if (ap?.count !== undefined && ap?.machine.label !== undefined && ap?.count !== 0) {
            newAnalysisPatientCount.push([ap.machine.label, ap.count]);
        }
    });
    setAnalysisCountPatient(newAnalysisPatientCount);
}, [schedulePatientCount]);

const options = {
    is3D: true,
    sliceText: 'value',
    tooltip: {
        text: 'value'
    }
};
// ...其他代码不变

这样修改后,饼图就会直接显示每个切片对应的具体数值,同时避免了状态更新的潜在问题。

内容的提问来源于stack exchange,提问作者Hiba Youssef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:01:18