multiline chart using d3.js
cool multiline chart using d3.js
by Sourabh Tewari
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"></script>
<!--1. toggle legend-->
CSS
body {
font-family: sans-serif;
background: #fff;
}
svg {
margin-top: 40px;
}
.axis path {
fill: none;
stroke: #777;
shape-rendering: crispEdges;
}
.axis text {
font-size: 11px;
opacity: 0.5;
}
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
/* style for grid */
.grid path,
.grid line {
fill: none;
stroke: rgba(0, 0, 0, 0.25);
shape-rendering: crispEdges;
}
.tick line {
stroke: #f5f5f5;
}
/* style for line label customization */
.lineLabel {
font-size: 12px;
}
/* style for tooltip customization */
div.tooltip {
position: absolute;
text-align: center;
padding: 10px;
font: 12px sans-serif;
border-radius: 8px;
pointer-events: none;
}
#xAxis g.tick line {
stroke: #f5f5f5;
stroke-dasharray: 3, 3;
}
#xAxis g.tick:nth-child(3n) line {
stroke: #e3e3e3;
stroke-dasharray: 0, 0;
}
JavaScript
// chart data
var chartConfig = {
lineConnectorLength:40,
axisLabel:{
xAxis : 'Date',
yAxis : 'Value'
},
lineLabel:{
height:20,
width:60,
},
data:[{
"sale": "202",
"year": "0"
}, {
"sale": "215",
"year": "1"
}, {
"sale": "179",
"year": "2"
}, {
"sale": "199",
"year": "3"
}, {
"sale": "149",
"year": "4"
}, {
"sale": "179",
"year": "5"
}, {
"sale": "157",
"year": "6"
}, {
"sale": "161",
"year": "7"
}, {
"sale": "159",
"year": "8"
}, {
"sale": "176",
"year": "10"
}],
data2:[{
"sale": "150",
"year": "0"
}, {
"sale": "155",
"year": "1"
}, {
"sale": "169",
"year": "2"
}, {
"sale": "149",
"year": "3"
}, {
"sale": "145",
"year": "4"
}, {
"sale": "144",
"year": "5"
}, {
"sale": "158",
"year": "6"
}, {
"sale": "140",
"year": "8"
}, {
"sale": "180",
"year": "10"
}]
};
// enviornment setup
var svgConfig = {
id:"mySvg",
width:700,
height:300,
margin : {
top: 20,
right: 20,
bottom: 20,
left: 100
}
};
// Define the div for the tooltip
var tooltipDiv = d3.select("body").append("div")
.attr("class", "tooltip");
// drawing
// append svg element
var bodySelection = d3.select("body");
var svgSelection = bodySelection.append("svg")
.attr("id", svgConfig.id)
.attr("width",svgConfig.width)
.attr("height",svgConfig.height);
// create x scale
xScale = d3.scale.linear()
.range([
svgConfig.margin.left,
svgConfig.width - svgConfig.margin.right
])
.domain([
d3.min(chartConfig.data, function(d) {return +d.year;}),
d3.max(chartConfig.data, function(d) {return...