Line chart - coding adventures
by BairDev
HTML
<div id="lineW">
</div>
CSS
#lineW {
width: 800px;
height: 350px;
border: 1px solid #ddd;
}
.line_0 {
stroke: #da0808;
stroke-width: 1px;
fill: none;
}
.line_1 {
stroke: #333;
stroke-width: 1px;
fill: none;
}
.x-axis path, .y-axis path {
stroke: #a0a0f0;
fill: none;
stroke-width: 2px;
}
.x-axis line, .y-axis line {
stroke: #a0a0f0;
shape-rendering: crispEdges;
fill: none;
stroke-width: 1px;
}
.x-axis text, .y-axis text {
font-size: 8px;
stroke: #a0a0f0;
stroke-width: 1px;
font-family: Arial, Helvetica, sans-serif;
}
JavaScript
function lineChart(widthHeight, lineWrapperId) {
if (!widthHeight || !(widthHeight instanceof Array) || widthHeight.length !== 2 || !widthHeight.every(function(wH) {
return typeof wH === 'number';
}) || (typeof lineWrapperId !== 'string') || !lineWrapperId.length) {
console.error("lineChart needs array with width and height and an lineWrapperId.", widthHeight, lineWrapperId);
return;
}
var basics = {
width: widthHeight[0],
height: widthHeight[1],
margin: 10
};
var parts = { // mostly functions, apart from the svg
scaleX: null,
scaleY: null,
axisX: null, // the drawn axis
axisY: null,
svg: null,
lines: {},
collectedLength: null,
concatedData: null
};
function setSVG() {
parts.svg = d3.select('#lineW').append('svg').attr(
{
width: basics.width,
height: basics.height
});
parts.svg.append('defs').append('clipPath') //add a clip
.attr('id', lineWrapperId)
.append('rect')
.attr({
width: basics.width + 'px',
height: basics.height + 'px'
});
parts.pathFrame = parts.svg.append('g') // add lines group
.attr('clip-path', 'url(#' + lineWrapperId + ')')
.attr('class', 'line-wrapper');
}
function addXAxis() {
// 0. create tickValues array
var tickValues = [];
if (parts.collectedLength instanceof Array) {
tickValues = d3.range(1, d3.max(parts.collectedLength));
} else {
console.error("Called addXAxis before any data are living?", parts.collectedLength);
}
// 1. create methods for axis
var xAxis = d3.svg.axis()
.scale(parts.scaleX)
.tickValues(tickValues)
.innerTickSize([])
.orient('top');
// 2. draw axis
if (!parts.axisX) {
parts.axisX = parts.svg.append('g')
.attr({
'class': 'x-axis',
transform: 'translate(0,' + (basics.height - basics.margin) + ')'
})
.call(xAxis); // leave out tick sizes for now
} else {
...