首页 > 解决方案 > D3 散点图返回 xy = NaN

问题描述

我收到以下控制台错误:

Error: <circle> attribute cy: Expected length, "NaN".

这导致我的圆形元素被赋值为 0 并呈现在屏幕顶部。

我的圈子被传递一个日期值作为 cy 而不是数字,我尝试使用两者scaleTime()scaleLinear()没有达到预期的效果。

<circle cx="41.9047619047619" cy="NaN" r="6" class="dot" data-xvalue="1995" data-yvalue="Mon Jan 01 1900 00:36:50 GMT+0000 (Greenwich Mean Time)"></circle>

代码

let width = 500;
let height = 500;
let margin = {left: 20, right: 20, top: 20, bottom: 20};
let timeFormat = d3.timeParse("%M:%S");

// select container and render svg canvas, set height and width.
const chart = d3.select('#container')
  .append('svg')
  .attr('height', height)
  .attr('width', width);

// Fetch data
d3.json('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/cyclist-data.json').then(data => {

// Find highest and lowest years in dataset
  const maxYear = d3.max(data, (d) => d.Year);
  const minYear = d3.min(data, (d) => d.Year);

// Parse time data
  data.forEach(d => {
    let timeParser = d3.timeParse('%M:%S')
    d.Time = timeParser(d.Time);
  });

// Define Scales
  let xScale = d3.scaleLinear() // try scaleTime afterwards to check
    .domain([minYear, maxYear])
    .range([margin.left, width - margin.right]);

  let yScale = d3.scaleTime()
    .domain([d3.extent(data, (d) => d.Time)])
    .range([0, height - margin.top])


// Render circles for each data point
  chart.selectAll('circle')
    .data(data)
    .enter()
    .append('circle')
    .attr('cx', (d) => xScale(d.Year))
    .attr('cy', (d) => yScale(d.Time))
    .attr('r', 6)
    .attr('class', 'dot')
    .attr('data-xvalue', (d) => d.Year)
    .attr('data-yvalue', (d) => d.Time)

})

我在解析时间数据时尝试了以下替代方法,但仍然出现相同的错误:

// Parse time data
  data.forEach(d => {
    let timeParser = d3.timeParse('%M:%S')
    d["Time"] = timeParser(d.Time);
  });
// Parse time data
  data.forEach(d => {
    let timeParser = d3.timeParse('%M:%S')
    d.Time = new Date(timeParser(d.Time));
  });

JSON数据供参考:

  {
    "Time": "36:50",
    "Place": 1,
    "Seconds": 2210,
    "Name": "Marco Pantani",
    "Year": 1995,
    "Nationality": "ITA",
    "Doping": "Alleged drug use during 1995 due to high hematocrit levels",
    "URL": "https://en.wikipedia.org/wiki/Marco_Pantani#Alleged_drug_use"
  },
  {
    "Time": "36:55",
    "Place": 2,
    "Seconds": 2215,
    "Name": "Marco Pantani",
    "Year": 1997,
    "Nationality": "ITA",
    "Doping": "Alleged drug use during 1997 due to high hermatocrit levels",
    "URL": "https://en.wikipedia.org/wiki/Marco_Pantani#Alleged_drug_use"
  },

标签: d3.js

解决方案


推荐阅读