d3.js - define grid line style with javascript - d3.js

I prefer to use javascript to draw graph without css file since it's more easy to copy one file here and there!
But I don't know how to translate grid line css to javascript!
Thanks if anyone can help! (grid line and grid path commented out now in css file)
console.clear()
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var valueline = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var datacsv = `date,close
1-May-12,58.13
30-Apr-12,53.98
27-Apr-12,67.00
26-Apr-12,89.70
25-Apr-12,99.00
24-Apr-12,130.28
23-Apr-12,166.70
20-Apr-12,234.98
19-Apr-12,345.44
18-Apr-12,443.34
17-Apr-12,543.70
16-Apr-12,580.13
13-Apr-12,605.23
12-Apr-12,622.77
11-Apr-12,626.20
10-Apr-12,628.44
9-Apr-12,636.23
5-Apr-12,633.68
4-Apr-12,624.31
3-Apr-12,629.32
2-Apr-12,618.63
30-Mar-12,599.55
29-Mar-12,609.86
28-Mar-12,617.62
27-Mar-12,614.48
26-Mar-12,606.98
`
var data = d3.csvParse(datacsv);
// Get the data
// d3.csv("data.csv").then(function(data) {
// process(data)
// });
process(data)
function process(data) {
var parseTime = d3.timeParse("%d-%b-%y");
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
// add the X gridlines
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(
d3.axisBottom(x)
.ticks(5)
//.tickSize(-height) xaxis grid line
.tickFormat("")
)
// add the Y gridlines
svg.append("g")
.attr("class", "grid")
.call(
d3.axisLeft(y)
.ticks(5)
.tickSize(-width)
.tickFormat("")
)
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline)
.attr('fill', 'none')
.attr('stroke','steelblue')
.attr('stroke-width',2)
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
}
/*
.grid line {
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}
.grid path {
stroke-width: 0;
}
*/
<script src="https://d3js.org/d3.v6.min.js"></script>

The d3 selection.style() method sets the style attribute of a given tag - allowing you to specify css style attributes. d3.selectAll() can be passed a css selector string, so this is:
.grid line {
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}
.grid path {
stroke-width: 0;
}
Is similar to:
d3.selectAll(".grid line")
.style("stroke","lightgrey")
.style("stroke-opacity",0.7)
.style("shape-rendering","crispEdges")
d3.selectAll(".grid path")
.style("stroke-width",0)
I say similar as the major difference is that by using .style() the elements have to already exist (otherwise we can't select them in order to modify them). So we could just place the above after the point you call the axis so we know the elements exist already:
console.clear()
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var valueline = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var datacsv = `date,close
1-May-12,58.13
30-Apr-12,53.98
27-Apr-12,67.00
26-Apr-12,89.70
25-Apr-12,99.00
24-Apr-12,130.28
23-Apr-12,166.70
20-Apr-12,234.98
19-Apr-12,345.44
18-Apr-12,443.34
17-Apr-12,543.70
16-Apr-12,580.13
13-Apr-12,605.23
12-Apr-12,622.77
11-Apr-12,626.20
10-Apr-12,628.44
9-Apr-12,636.23
5-Apr-12,633.68
4-Apr-12,624.31
3-Apr-12,629.32
2-Apr-12,618.63
30-Mar-12,599.55
29-Mar-12,609.86
28-Mar-12,617.62
27-Mar-12,614.48
26-Mar-12,606.98
`
var data = d3.csvParse(datacsv);
// Get the data
// d3.csv("data.csv").then(function(data) {
// process(data)
// });
process(data)
function process(data) {
var parseTime = d3.timeParse("%d-%b-%y");
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
// add the X gridlines
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(
d3.axisBottom(x)
.ticks(5)
//.tickSize(-height) xaxis grid line
.tickFormat("")
)
// add the Y gridlines
svg.append("g")
.attr("class", "grid")
.call(
d3.axisLeft(y)
.ticks(5)
.tickSize(-width)
.tickFormat("")
)
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline)
.attr('fill', 'none')
.attr('stroke','steelblue')
.attr('stroke-width',2)
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
d3.selectAll(".grid line")
.style("stroke","lightgrey")
.style("stroke-opacity",0.7)
.style("shape-rendering","crispEdges")
d3.selectAll(".grid path")
.style("stroke-width",0)
}
/*
{
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}
.grid path {
stroke-width: 0;
}
*/
<script src="https://d3js.org/d3.v6.min.js"></script>

Related

Formatting year in D3 V4 to remove commas

I am creating a line chart in D3 v4.
The x-axis is showing the year with commas like 1,998 and 1,999 instead of 1998 and 1999 etc. It is addig the thousand comma which is what I am trying to remove.
I am trying to remove the commas, but I have not been able to. tickformat is not working in v4.
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
// set the dimensions and margins of the graph
var margin = {top: 50, right: 50, bottom: 100, left: 80},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// define the line
var valueline = d3.line()
.x(function(d) { return x(d.Year); })
.y(function(d) { return y(d.Amount); });
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Get the data
d3.csv("australia.csv", function(error, data) {
if (error) throw error;
// format the data
data.forEach(function(d) {
d.Year = d.Year;
d.Amount = +d.Amount;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.Year}));
y.domain([0, d3.max(data, function(d) { return d.Amount; })]);
// Add the valueline path.
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline);
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// text label for the x axis
svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," +
(height + margin.top) + ")")
.style("text-anchor", "middle")
.text("Year");
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
// text label for the y axis
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Amount");
});
</script>
</body>
And here is my csv file:
Year,Amount
1998,103323
1999,57914.9
2003,297.969
2004,921253.8
2007,169869.2
2008,44685.5
2010,86084.5
Thanks,
You should use scaleTime for x axis, not scaleLinear:
var x = d3.scaleTime().range([0, width]);
You also should process your dataset this way:
var parseTime = d3.timeParse("%Y");
data.forEach(function(d) {
d.Year = parseTime(d.Year);
d.Amount = +d.Amount;
});
Check working example in the hidden snippet below:
var dataAsCsv = `Year,Amount
1998,103323
1999,57914.9
2003,297.969
2004,921253.8
2007,169869.2
2008,44685.5
2010,86084.5`;
// set the dimensions and margins of the graph
var margin = {top: 50, right: 50, bottom: 100, left: 80},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// define the line
var valueline = d3.line()
.x(function(d) { return x(d.Year); })
.y(function(d) { return y(d.Amount); });
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var data = d3.csvParse(dataAsCsv);
var parseTime = d3.timeParse("%Y");
// format the data
data.forEach(function(d) {
d.Year = parseTime(d.Year);
d.Amount = +d.Amount;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.Year}));
y.domain([0, d3.max(data, function(d) { return d.Amount; })]);
// Add the valueline path.
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline);
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// text label for the x axis
svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," +
(height + margin.top) + ")")
.style("text-anchor", "middle")
.text("Year");
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
// text label for the y axis
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Amount");
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>

How to synchronize animation of path and area?

I'm getting stuck with the D3.js v4's animation of both line & area:
It's ok to do the animation separately for line & area
When 2 animations are combined, even at the same transition duration, they do not occur together.
For the reason of styling, I cannot drop the line away.
See the illustration below:
To make thing like above, I do 2 big steps:
Do animation for line via setting the properties stroke-dasharrow and stroke-dashoffset. (Inspired from Visual Cinnamon)
Do animation for area via tweaking parameters for d3.area() function (Inspired from other Stackoverlfow post)
The result is rather disappointing because line and area underneath do not appear in parallel.
My target is to mimic the Highchart library, see an example here, and its illustration below:
It seems the Highchart library uses a different animation technique, because during DOM inspection, there is no sign of any change for the DOM paths along the animation.
Appreciated if anyone could suggest me some ideas to experiment with.
My code sample is below:
let animationDuration = 5000;
// set the dimensions and margins of the graph
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 480 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
// parse the date / time
var parseTime = d3.timeParse("%d-%b-%y");
// set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// define the area
var area = function (datum, boolean) {
return d3.area()
.y0(height)
.y1(function (d) { return boolean ? y(d.close) : y(d.close); })
.x(function (d) { return boolean ? x(d.date) : 0; })
(datum);
}
// define the line
var valueline = d3.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.close); });
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var data = d3.csvParse(d3.select("pre#data").text());
data.reverse();
// format the data
data.forEach(function (d) {
d.date = parseTime(d.date);
d.close = +d.close;
});
// scale the range of the data
x.domain(d3.extent(data, function (d) { return d.date; }));
y.domain([0, d3.max(data, function (d) { return d.close; })]);
// add the area
svg.append("path")
.data([data])
.attr("class", "area")
.attr("d", d => area(d, false))
.attr("fill", "lightsteelblue")
.transition()
.duration(animationDuration)
.attr("d", d => area(d, true));
// add the valueline path.
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline)
.style("stroke-dasharray", d => {
let path = document.querySelector(".line");
const totalLength = path.getTotalLength();
return `${totalLength} ${totalLength}`;
})
.style("stroke-dashoffset", d => {
let path = document.querySelector(".line");
const totalLength = path.getTotalLength();
return `${totalLength}`;
})
.transition()
.duration(animationDuration)
.style("stroke-dashoffset", 0);
// add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
pre#data {display:none;}
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="data">
date,close
1-May-12,58.13
30-Apr-12,53.98
27-Apr-12,67.00
26-Apr-12,89.70
25-Apr-12,99.00
24-Apr-12,130.28
23-Apr-12,166.70
20-Apr-12,234.98
19-Apr-12,345.44
18-Apr-12,443.34
17-Apr-12,543.70
16-Apr-12,580.13
13-Apr-12,605.23
12-Apr-12,622.77
11-Apr-12,626.20
10-Apr-12,628.44
9-Apr-12,636.23
5-Apr-12,633.68
4-Apr-12,624.31
3-Apr-12,629.32
2-Apr-12,618.63
30-Mar-12,599.55
29-Mar-12,609.86
28-Mar-12,617.62
27-Mar-12,614.48
26-Mar-12,606.98
</pre>
There is a way to animate both the line and the area, using a custom interpolator.
However, since your goal is to mimic that Highcharts animation you linked, there is a way easier alternative: use a <clipPath>.
In my proposed solution we create the area and the line the regular way. However, we reference a clipping path...
.attr("clip-path", "url(#clip)");
...in both area and line. The clipping path is created with 0 width:
var clip = svg.append("clipPath")
.attr("id", "clip");
var clipRect = clip.append("rect")
.attr("width", 0)
Then, after that, it's just a matter of applying the transition to the clipping path:
clipRect.transition()
.duration(5000)
.ease(d3.easeLinear)
.attr("width", someValue)
Here is a demo:
var svg = d3.select("svg");
var data = d3.range(30).map(d => Math.random() * 150);
var clip = svg.append("clipPath")
.attr("id", "clip");
var clipRect = clip.append("rect")
.attr("width", 0)
.attr("height", 150)
var lineGenerator = d3.line()
.x((_, i) => i * 10)
.y(d => d)
.curve(d3.curveMonotoneX)
var areaGenerator = d3.area()
.x((_, i) => i * 10)
.y1(d => d)
.y0(150)
.curve(d3.curveMonotoneX)
svg.append("path")
.attr("d", areaGenerator(data))
.attr("class", "area")
.attr("clip-path", "url(#clip)");
svg.append("path")
.attr("d", lineGenerator(data))
.attr("class", "line")
.attr("clip-path", "url(#clip)");
clipRect.transition()
.duration(5000)
.ease(d3.easeLinear)
.attr("width", 300)
.line {
fill: none;
stroke: #222;
stroke-width: 2px;
}
.area {
fill: limegreen;
stroke: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
And here is your code with those changes:
let animationDuration = 5000;
// set the dimensions and margins of the graph
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = 480 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
// parse the date / time
var parseTime = d3.timeParse("%d-%b-%y");
// set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// define the area
var area = function(datum, boolean) {
return d3.area()
.y0(height)
.y1(function(d) {
return boolean ? y(d.close) : y(d.close);
})
.x(function(d) {
return boolean ? x(d.date) : 0;
})
(datum);
}
// define the line
var valueline = d3.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.close);
});
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var clip = svg.append("clipPath")
.attr("id", "clip");
var clipRect = clip.append("rect")
.attr("width", 0)
.attr("height", height);
var data = d3.csvParse(d3.select("pre#data").text());
data.reverse();
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
});
// scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return d.close;
})]);
// add the area
svg.append("path")
.data([data])
.attr("class", "area")
.attr("d", d => area(d, true))
.attr("fill", "lightsteelblue")
.attr("clip-path", "url(#clip)");
// add the valueline path.
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline)
.attr("clip-path", "url(#clip)");
// add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
clipRect.transition()
.duration(5000)
.ease(d3.easeLinear)
.attr("width", width)
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
pre#data {
display: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="data">
date,close
1-May-12,58.13
30-Apr-12,53.98
27-Apr-12,67.00
26-Apr-12,89.70
25-Apr-12,99.00
24-Apr-12,130.28
23-Apr-12,166.70
20-Apr-12,234.98
19-Apr-12,345.44
18-Apr-12,443.34
17-Apr-12,543.70
16-Apr-12,580.13
13-Apr-12,605.23
12-Apr-12,622.77
11-Apr-12,626.20
10-Apr-12,628.44
9-Apr-12,636.23
5-Apr-12,633.68
4-Apr-12,624.31
3-Apr-12,629.32
2-Apr-12,618.63
30-Mar-12,599.55
29-Mar-12,609.86
28-Mar-12,617.62
27-Mar-12,614.48
26-Mar-12,606.98
</pre>

d3js stack chart: how to add text on each layer?

In the example of Stacked Area via Nest, I would like to add text on each layer. Like
The position of the text doesn't really matters, just being center-right.
You can do something like this:
0) Calculte the center of the path using the function below:
function getMyCentroid(element) {
var bbox = element.getBBox();
return [bbox.x + bbox.width / 2, bbox.y + bbox.height / 2];
}
1) Next select all path and calculate its center.
2) Append a text and position it at the center svg.append("text")
3) Set the text associated with the path like this .text(d3.select(d).data()[0].key);
d3.selectAll(".layer")[0].forEach(function(d) {
var centroid = getMyCentroid(d);
svg.append("text").attr("x", centroid[0]).attr("y", centroid[1]).text(d3.select(d).data()[0].key);
})
var format = d3.time.format("%m/%d/%y");
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var z = d3.scale.category20c();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.days);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var stack = d3.layout.stack()
.offset("zero")
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.value; });
var nest = d3.nest()
.key(function(d) { return d.key; });
var area = d3.svg.area()
.interpolate("cardinal")
.x(function(d) { return x(d.date); })
.y0(function(d) { return y(d.y0); })
.y1(function(d) { return y(d.y0 + d.y); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("https://gist.githubusercontent.com/cyrilcherian/e6f56b1b9337142c0bde/raw/8b1728849e193db0e8b960ecb750062f4e0cb487/data.csv", function(error, data) {
if (error) throw error;
data.forEach(function(d) {
d.date = format.parse(d.date);
d.value = +d.value;
});
var layers = stack(nest.entries(data));
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
svg.selectAll(".layer")
.data(layers)
.enter().append("path")
.attr("class", "layer")
.attr("d", function(d) { return area(d.values); })
.style("fill", function(d, i) { return z(i); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function getMyCentroid(element) {
var bbox = element.getBBox();
return [bbox.x + bbox.width / 2, bbox.y + bbox.height / 2];
}
d3.selectAll(".layer")[0].forEach(function(d) {
var centroid = getMyCentroid(d);
svg.append("text").attr("x", centroid[0]).attr("y", centroid[1]).text(d3.select(d).data()[0].key).style("fill", "red");
})
});
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Hope this helps!

D3 Parsing Error

This is likely a very easy question (but I'm new to D3 and trying to go through some of the examples to get a better understanding of how it works). I'm trying to modify one of the base examples for D3 (http://bl.ocks.org/mbostock/1667367). I've basically kept everything the same... I'm just trying to use a different csv file with my own data (vs. the S&P 500 stock data). In the example file, the csv file has a date (month year) and a stock price. In my data, I have a UTC time stamp and a light value (between 0-1000). Here's a small example of the csv:
date, light
2013-01-01T09:00:00.000Z,554.22
2013-01-01T09:01:00.000Z,480.83
2013-01-01T09:02:00.000Z,433.19
2013-01-01T09:03:00.000Z,596.89
2013-01-01T09:04:00.000Z,421.78
2013-01-01T09:05:00.000Z,461.23
2013-01-01T09:06:00.000Z,560.04
When, I run my code I get an error in the console window saying I have a parsing error (not sure if it's getting caught up in parsing the data or the light value)... Does anyone see a problem with how I'm setting up the csv file (or how I might be parsing it incorrectly)? Here's the D3 code I'm working with.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
}
path {
fill: steelblue;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.brush .extent {
stroke: #fff;
fill-opacity: .125;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 10, right: 10, bottom: 100, left: 40},
margin2 = {top: 430, right: 10, bottom: 20, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
height2 = 500 - margin2.top - margin2.bottom;
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;
var x = d3.time.scale().range([0, width]),
x2 = d3.time.scale().range([0, width]),
y = d3.scale.linear().range([height, 0]),
y2 = d3.scale.linear().range([height2, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom"),
xAxis2 = d3.svg.axis().scale(x2).orient("bottom"),
yAxis = d3.svg.axis().scale(y).orient("left");
var brush = d3.svg.brush()
.x(x2)
.on("brush", brush);
var area = d3.svg.area()
.interpolate("monotone")
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.light); });
var area2 = d3.svg.area()
.interpolate("monotone")
.x(function(d) { return x2(d.date); })
.y0(height2)
.y1(function(d) { return y2(d.light); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
d3.csv("Light.csv", function(error, data) {
console.log(data);
data.forEach(function(d) {
d.date = parseDate(d.date);
//d.light = +d.light;
//console.log(d);
});
x.domain(d3.extent(data.map(function(d) { return d.date; })));
y.domain([0, d3.max(data.map(function(d) { return d.light; }))]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("path")
.datum(data)
.attr("clip-path", "url(#clip)")
.attr("d", area);
focus.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "y axis")
.call(yAxis);
context.append("path")
.datum(data)
.attr("d", area2);
context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", height2 + 7);
});
function brush() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.select("path").attr("d", area);
focus.select(".x.axis").call(xAxis);
}
</script>
In the header of your csv file, the "light" header has an extra space in front of it. That leads to processing problems with d3.csv.
data.forEach(function(d) {
d.date = parseDate(d.date);
d.light = +d.light; // won't be able to access the light column data with the space
d.light = d[' light']; // this would work if you can't fix the header at the csv source
});
Hmmm, maybe I'll submit a patch to d3 to fix this...
You are probably getting that error because of your time format specification -- there is no %L placeholder (see the documentation). This should work.
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.000Z").parse;

Simple D3 line chart example

I'm a D3 newbie and having a slow time getting up to speed on this library. I am trying to get this simple D3 area chart to work but am having some trouble displaying the actual area it self. I can get the axis to display correctly with the right ranges for the data, but no area displays on the graph itself.
I am feeding it JSON data that looks like this and it appears to be consuming the data fine as best as I can tell.
[{"Date":"Date","Close":"Close"},{"Date":"20130125","Close":"75.03"},{"Date":"20130124","Close":"75.32"},{"Date":"20130123","Close":"74.29"},{"Date":"20130122","Close":"74.16"},{"Date":"20130118","Close":"75.04"},{"Date":"20130117","Close":"75.26"},{"Date":"20130116","Close":"74.34"},{"Date":"20130115","Close":"76.94"},{"Date":"20130114","Close":"76.55"}]
This is my code
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y%m%d").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var area = d3.svg.area()
.x(function(d) { return x(d.Date); })
.y0(height)
.y1(function(d) { return y(d.Close); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json('JSONstockPriceOverTime.php', function (data) {
data.forEach(function(d) {
d.Date = parseDate(d.Date);
d.Close = +d.Close;
});
x.domain(d3.extent(data, function(d) { return d.Date; }));
y.domain([0, d3.max(data, function(d) { return d.Close; })]);
svg.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
});
And I have this style applied
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.area {
fill: steelblue;
}
</style>
Remove the starting part of the json (JSONstockPriceOverTime.php) file;
{"Date":"Date","Close":"Close"},
Since it has the 'Date' and 'Close' variables defined as part of the json format, you won't be required to include header information like a csv file, and add 'error' into your json load line
d3.json("JSONstockPriceOverTime.php", function(error, data) {
and you should be all go (worked for me).
You're making good progress.

Resources