繁体   English   中英

d3.js:5942错误:的值无效 <g> 属性transform =“ translate(NaN,0)”

[英]d3.js:5942 Error: Invalid value for <g> attribute transform=“translate(NaN,0)”

使用d3.js v3.55,crossfilter.js v1.311和dc.js v1.73,并尝试构建一个reduce函数,该函数返回平均值而不是总和或计数。 内置的reduceSum可以正常工作,但是基于互联网上的许多示例,当我尝试添加自己的reduce函数时。 我收到消息:d3.js:5942错误:属性transform =“ translate(NaN,0)”的无效值d3.js:8718错误:属性width =“ NaN”的无效值

这是我在不消除任何重要信息的情况下尽可能减少的代码:

<script type="text/javascript">
//
// Create the Chart Objects
//
var GeoZoneChart               = dc.rowChart("#chart-geo-zone");
var pdcData = [
{GeoZone: 'New York Metro', PDCLast365: 0.43}, 
{GeoZone: 'New York Metro', PDCLast365: 0.427}, 
{GeoZone: 'New York Metro', PDCLast365: 0.418}, 
{GeoZone: 'Los Angeles Metro', PDCLast365: 0.4085}, 
{GeoZone: 'Los Angeles Metro', PDCLast365: 0.40565}, 
{GeoZone: 'Chicago Metro', PDCLast365: 0.46789457}, 
{GeoZone: 'Chicago Metro', PDCLast365: 0.46366023}, 
{GeoZone: 'Chicago Metro', PDCLast365: 0.447781455}
];
//
// normalize/parse data
//   in this case, turn the decimel into a percentage
pdcData.forEach(function(d) {
    d.PDCLast365 = d.PDCLast365 * 100;
    d.PDCLast365 = d.PDCLast365.toFixed(2);
});

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function reduceAddAvg(attr) {
  return function(p,v) {
    if (isNumeric(v[attr]) ){
        ++p.count;
        p.sum += v[attr];
        p.avg = p.sum/p.count;
    }
    return p;
  };
}
function reduceRemoveAvg(attr) {
  return function(p,v) {
    if (isNumeric(v[attr]) ){
        --p.count;
        p.sum -= v[attr];
        p.avg = p.sum/p.count;
    }
    return p;
  };
}
function reduceInitAvg() {
  return {count:0, sum:0, avg:0};
}

//
// set crossfilter
//
var ndx = crossfilter(pdcData),
    GeoZoneDim           = ndx.dimension(function(d) {return d.GeoZone;}),
    PDCLast365PerGeoZone = 
          GeoZoneDim.group().reduce(
            reduceAddAvg('PDCLast365'), 
            reduceRemoveAvg('PDCLast365'), 
            reduceInitAvg);


GeoZoneChart
    .width(400).height(200)
    .dimension(GeoZoneDim)
    .group(PDCLast365PerGeoZone)
    .elasticX(true);

dc.renderAll();
</script>

p.count降至零时,您需要一个保护p.count 所以:

function reduceRemoveAvg(attr) {
  return function(p,v) {
    if (isNumeric(v[attr]) ){
        --p.count;
        p.sum -= v[attr];
        p.avg = p.count ? p.sum/p.count : 0;
    }
    return p;
  };
}

如果您可以在SO或dc.js网站或用户组上指出任何此类不良示例,则必须这样做。

编辑:我不确定它将在这里产生什么效果,但是toFixed()实际上返回一个字符串,而不是一个数字。 然后您的isNumeric测试值是否可以转换为数字,而不是是否为数字。 因此,您可能最终得到的是字符串连接而不是加法。

就像我在下面说的那样,解决这个问题的正确方法是在reduce函数中放置断点,然后查看实际计算的内容。

当范围不是数组时,我通常会收到该错误。

检查.range接收的变量是否为实际数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM