how to create simple line chart using d3js
lets learn to create line chart using d3.js by simple steps. go through comments to learn line chart
by Dhanesh Mane
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"></script>
<p>Lets learn to create d3js line chart in simple steps</p>
CSS
.axis path {
fill: none;
stroke: #777;
shape-rendering: crispEdges;
}
.axis text {
font-family: Lato;
font-size: 13px;
}
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.grid path,
.grid line {
fill: none;
stroke: rgba(0, 0, 0, 0.25);
shape-rendering: crispEdges;
}
.tick line{
opacity: 0.2;
}
JavaScript
// chart data
var chartConfig = { data:[{ "sale": "190", "year": "2000" }, { "sale": "215", "year": "2001" }, { "sale": "179", "year": "2002" }, { "sale": "199", "year": "2003" }, { "sale": "134", "year": "2004" }, { "sale": "176", "year": "2010" }] };
// enviornment setup
var svgConfig = {
id:"mySvg",
width:600,
height:300,
margin : {
top: 20,
right: 20,
bottom: 20,
left: 50
}
};
// 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 +d.year;}) ]);
// create y scale
yScale = d3.scale.linear()
.range([svgConfig.height - svgConfig.margin.top, svgConfig.margin.bottom])
.domain([ d3.min(chartConfig.data, function(d) {return +d.sale;}), d3.max(chartConfig.data, function(d) {return +d.sale;}) ]);
//let's create the axes using the scales
xAxis = d3.svg.axis()
.scale(xScale)
.tickFormat(d3.format("d"))
.innerTickSize(-svgConfig.height);
yAxis = d3.svg.axis()
.orient("left")
.scale(yScale)
.innerTickSize(-svgConfig.width);
// add xaxis to chart - it will add it to top of the svg
svgSelection.append("svg:g")
.attr("id","xAxis")
.attr("class","axis")
.call(xAxis);
// The X axis is drawn but it has some issues. First, we need to position it vertically downwards using transform property
d3.select("#xAxis")
.attr("transform", "translate(0," + (svgConfig.height - svgConfig.margin.bottom) + ")");
// add yaxis to chart, but this will...