Reputation: 501
I'm attempting to make a simple line chart in d3 v5 and I'm having trouble with the x axis.
Here's a sample of my 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",
}
Here I try to parse my keys as date objects
//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]);
});
After looping through my dates, they are date objects that look like this:
Wed Feb 18 2015 00:00:00 GMT-0600 (Central Standard Time)
Then I set my mins and maxs:
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)
And set my scale like this:
//x scale
var xScale = d3.scaleTime()
.domain([minDate,maxDate])
.range(0,width);
Then I tried to display my axis like this
//x axis
var xAxis = d3.axisBottom(xScale);
svg.append('g')
.call(xAxis);
It's currently giving me this error when I try to call the x axis:
Error: <path> attribute d: Expected number, "MNaN,6V0.5HNaNV6".
My path wants numbers? But I just made them javascript date objects. I used to dabble in d3 v3, but I'm pretty rusty. Any links to good v5 examples would also be much appreciated. Thanks!
Upvotes: 1
Views: 719
Reputation: 28673
why don't you parse the dates like this
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>
Upvotes: 1
Reputation: 501
I forgot the square brackets on my range...
//x scale
var xScale = d3.scaleTime()
.domain([minDate,maxDate])
.range(0,width);
Should have been
//x scale
var xScale = d3.scaleTime()
.domain([minDate,maxDate])
.range([0,width]);
Shout out to this post for the answer: D3.js error using timescale (path is NaN)
Now on to the next problem...
Upvotes: 1