December 24, 2012

Super duper simple D3 line graph

I have been trying to find a REALLY stupid sipmle example of a line graph with d3js to no avail, so here is a 3-liner...

<title>super simple d3 line</title>
.line {
  fill: none;
  stroke: #00F;
  stroke-width: 2px;
<script src=""></script>
<script src=""></script>

var data = [0,2,4,6,8,10,8,6,4,2,4,6,8,6,4,6,6,6,6],
width = 300,
    height = 180,
x = d3.scale.linear().domain([0, data.length]).range([0, width]),
    y = d3.scale.linear().domain([0, d3.max(data)]).range([height,0]);

  add a visualisation,
  select the body tag,
  join the data array to to the body tag for our next data driven moves,
  append an svg container tag,
  give it the right width,
  give it the right height as well,
var visualisation = d3

this is the line to put on the graph
append a path tag as a child of the svg tag we added to the body tag,
apply css style to make the line blue
    .attr("class", "line")
    .attr("d", d3.svg.line()
    .x(function(d,i) {return x(i);})
    .y(function(d) {return y(d); }));

And you get ... this


  1. Excellent program code, thank you for sharing them. I know how to make good templates such as these It is best to take a ready-made template and spy a piece of code and add it to your code. This is the key to success.

  2. I suggest adding one more site to your list, where you can download free templates for professional presentations