我正在尝试在d3 v5中制作简单的折线图,而x轴出现问题。
这是我的数据样本
n
在这里,我尝试将键解析为日期对象
{
"2015-05-02":"1",
"2015-05-03":"2",
"2015-05-04":"1",
"2015-05-13":"3",
"2015-05-15":"2",
"2015-05-16":"2",
"2015-05-20":"1",
"2015-05-26":"11",
"2015-05-27":"1",
"2015-05-28":"7",
"2015-05-29":"260",
}
遍历我的日期后,它们是日期对象,如下所示:
//attempting to parse dates
//the dates are strings (eg. 2015-02-18)
dates = d3.keys(data);
$.each(dates, function(thisDate){
var formatDate = d3.timeParse("%Y-%m-%d");
dates[thisDate] = formatDate(dates[thisDate]);
});
然后我设置我的最小和最大:
Wed Feb 18 2015 00:00:00 GMT-0600 (Central Standard Time)
像这样设置我的体重秤:
minDate = d3.min(dates); //Wed Feb 18 2015 00:00:00 GMT-0600 (Central Standard Time)
maxDate = d3.max(dates); //Sat Dec 09 2017 00:00:00 GMT-0600 (Central Standard Time)
然后我试图显示这样的轴
//x scale
var xScale = d3.scaleTime()
.domain([minDate,maxDate])
.range(0,width);
当我尝试调用x轴时,当前会出现此错误:
//x axis
var xAxis = d3.axisBottom(xScale);
svg.append('g')
.call(xAxis);
我的道路上要数字吗?但是我只是使它们成为javascript date对象。我曾经涉猎d3 v3,但是我很生锈。任何指向优秀v5示例的链接也将不胜感激。 谢谢!
答案 0 :(得分:1)
为什么不解析这样的日期
var formatDate = d3.timeParse("%Y-%m-%d");
var dates = d3.keys(data).map( d => formatDate(d) );
var xScale = d3.scaleTime()
.domain(d3.extent(dates))
.range([0,width]);
var data = {
"2015-05-02":"1",
"2015-05-03":"2",
"2015-05-04":"1",
"2015-05-13":"3",
"2015-05-15":"2",
"2015-05-16":"2",
"2015-05-20":"1",
"2015-05-26":"11",
"2015-05-27":"1",
"2015-05-28":"7",
"2015-05-29":"260"
};
var width = 500;
var formatDate = d3.timeParse("%Y-%m-%d");
var dates = d3.keys(data).map( d => formatDate(d) );
var xScale = d3.scaleTime()
.domain(d3.extent(dates))
.range([0,width]);
console.log('xScale-domain', xScale.domain());
<script src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script>
答案 1 :(得分:1)
我忘记了我范围内的方括号...
//x scale
var xScale = d3.scaleTime()
.domain([minDate,maxDate])
.range(0,width);
应该是
//x scale
var xScale = d3.scaleTime()
.domain([minDate,maxDate])
.range([0,width]);
为这篇文章大声喊叫:D3.js error using timescale (path is NaN)
现在继续下一个问题...