求助解决ApexCharts控制台<g>属性transform的NaN错误
问题
使用ApexCharts实现饼图,通过API获取状态码、计数和状态名称填充数据,点击图例可打开模态框加载对应详情,功能正常但控制台持续报错:
Error:
<g>attribute transform: Expected number, "translate(NaN, 0) scale(1)".
相关代码:
$(document).ready(function () { var codeChartData = @Html.Raw(Json.Serialize(codeList)); console.log(codeChartData); var seriesData = codeChartData.map(item => parseInt(item.count)); var options = { chart: { type: 'pie', height: 600, events: { legendClick: function (chartContext, seriesIndex, config) { handleLegendClick(chartContext, seriesIndex, config, codeChartData); } } }, series: seriesData, labels: codeChartData.map(item => item.statusName), theme: { mode: 'light', palette: 'palette1' }, legend: { position: 'right', onItemClick: { toggleDataSeries: false } }, plotOptions: { pie: { expandOnClick: false } }, dataLabels: { enabled: false }, responsive: [{ breakpoint: 480, options: { chart: { width: 200 }, legend: { position: 'bottom' } } }] }; var chart = new ApexCharts(document.querySelector("#errorCountChartdiv"), options); chart.render(); }); function handleLegendClick(chartContext, seriesIndex, config, codeChartData) { var statusCode = codeChartData[seriesIndex].statusCode; console.log("Clicked seriesIndex:", seriesIndex); console.log("StatusCode:", statusCode); $('#errorDetailModal').modal('show'); $("#errorDetailModalTitle").html(chartContext.w.config.labels[seriesIndex]); $("#errorDetailModalBody").html("<i>Loading...</i>"); $.post("/Dashboard/ErrorDetails", { code: statusCode, fromTime: "@ViewBag.ErrorFromTime", toTime: "@ViewBag.ErrorToTime", endPoint: "@ViewBag.endPoint", i_customer: "@ViewBag.i_customer", i_account: "@ViewBag.i_account", ingress_adjacency: "@ViewBag.ingress_adjacency" }, function (data) { $("#errorDetailModalBody").html(data); }); return false; }
解决方法
该报错源于饼图布局计算时出现NaN值,按以下步骤修复:
校验series数据有效性
parseInt(item.count)可能返回NaN(如item.count为空、非数字格式),导致series数组存在无效值。修改数据生成逻辑:// 过滤无效数据并确保数值合法 const validEntries = codeChartData.filter(item => { const count = parseInt(item.count); return !isNaN(count) && count > 0; }); var seriesData = validEntries.map(item => parseInt(item.count)); var labels = validEntries.map(item => item.statusName); // 后续options中替换对应的series和labels var options = { // ...其他配置 series: seriesData, labels: labels, // ...其他配置 }修正legendClick事件阻止默认行为的方式
原代码返回false可能干扰ApexCharts内部布局计算,改用官方推荐的阻止方式:events: { legendClick: function (chartContext, seriesIndex, config) { handleLegendClick(chartContext, seriesIndex, config, validEntries); config.preventDefault(); // 替代return false } }确保容器元素尺寸正常
检查#errorCountChartdiv元素是否存在,添加基础样式避免尺寸异常:#errorCountChartdiv { width: 100%; min-width: 300px; }升级ApexCharts版本
旧版本存在饼图图例交互的布局计算bug,升级到最新稳定版可解决此类问题。
内容的提问来源于stack exchange,提问作者Hardik Singh
相关产品推荐
相关产品推荐

