'Date data not parsing properly d3
I have data in this format
Object {date: "2018-10-02T04:00Z", hours_of_sleep: "1.95"}
and am trying to draw a line, but it seems like d3 isn't parsing the dates correctly
{
const svg = d3.create('svg')
.attr('width', w)
.attr('height', h);
const margin = {
left: 30,
right: 20,
top: 20,
bottom: 20
};
const yScale = d3.scaleLinear()
.domain([0, 12])
.range([h - margin.bottom, margin.top]);
const xScale = d3.scaleTime()
.domain([(new Date("2018-09-26T04:00Z")), (new Date("2018-10-02T04:00Z"))])
.range([margin.left, w - margin.right]);
const xAxis = d3.axisBottom(xScale)
.ticks(d3.timeDay.every(1))
.tickFormat(d3.timeFormat('%a'));
const xAxisGroup = svg.append('g')
.attr('transform', `translate(0, ${h - 20})`)
.call(xAxis);
const yAxis = d3.axisLeft(yScale);
const yAxisGroup = svg.append('g')
.attr('transform', `translate(30, 0)`)
.call(yAxis);
const line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.sleep));
const dString = line(dataset);
svg.append('path')
.datum(dataset) // NOTICE: .datum() rather than .data()
.classed('line', true)
.attr('d', line)
.style('fill', 'none')
.style('stroke', 'steelblue')
.style('stroke-width', '2px');
svg.selectAll('.dot')
.data(dataset, d => d.hours_of_sleep)
.join('circle')
.attr('cx', d => xScale(d.date))
.attr('cy', d => yScale(d.hours_of_sleep))
.attr('r', 4)
.style('fill', 'steelblue');
return svg.node()
}
All the data exists properly on the Y axis, but not the X axis, please help
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
