我收到以下控制台错误:
Error: <circle> attribute cy: Expected length, "NaN".
这导致我的圆元素被赋值为0并呈现在屏幕顶部。
我的圈子正在传递Date值作为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"
},