Raspberry Pi Pico Tips and Tricks

Tuesday, 11 December 2012

Starting with a basic D3 line graph


Basic Graph

How I'll make a start is to provide the full code for a simple graph and then we can explain it piece by piece.

Here's what the basic graph looks like;
And here's the code that make it happen;
<!DOCTYPE html>
<meta charset="utf-8">
<style>

body { font: 12px Arial;}

path { 
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
}

.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}

</style>
<body>
<script type="text/javascript" src="d3/d3.v3.js"></script>

<script>

var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

var parseDate = d3.time.format("%d-%b-%y").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").ticks(5);

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);

var valueline = d3.svg.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 + ")");

// Get the data
d3.tsv("data/data.tsv", function(error, data) {
    data.forEach(function(d) {
        d.date = parseDate(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; })]);

    svg.append("path")      // Add the valueline path.
        .attr("d", valueline(data));

    svg.append("g")         // Add the X Axis
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")         // Add the Y Axis
        .attr("class", "y axis")
        .call(yAxis);

});

</script>
</body>
Once we've finished explaining these parts, we'll start looking at what we need to add in and adjust so that we can incorporate other useful functions that are completely reusable in other diagrams as well.

The end point being something hideous like the following;
I say hideous since the graph is not intended to win any beauty prizes, but there are several components to it which some people may find useful (gridlines, area fill, axis label, drop shadow for text, title, text formatting).

So, we can break the file down into component parts. I'm going to play kind of fast and loose here, but never fear, it'll all make sense.

The above description (and heaps of other stuff) is in the D3 Tips and Tricks document that can be accessed from the downloads page of d3noob.org.

8 comments:

  1. Thanks! This is exactly what I was looking for.

    ReplyDelete
  2. So I believe I have WAMP working properly, but I haven't got this example to work...page 8 to page 9 skip a few steps for people who have no idea how this stuff works! I copied this code into notepad and saved it as a .html file in the d3 subfolder, (you should mention data.tsv is available for download on the website in the pdf and in this blog post!)

    Once I have this saved as an html file and the data.tsv file in the proper location, should I be able to go to: http://localhost/webserver/d3/ and see this graph? That doesn't work for me.

    Thanks for all this work, it's awesome!

    ReplyDelete
    Replies
    1. Cheers for persevering. I think you're on the right track, but unfortunately I won't be able to assist from this end for a few days. You should be able to navigate to your HTML file from the browser if it's configured correctly. And if you can get to the file, it will be down to the data as to whether or not it displays. Good suggestion on the mention in the PDF for the files. Unfortunately I wrote that part before putting the files on line. Good luck!

      Delete
    2. I got it working! So awesome. I have been looking at d3 for a week and your guide was the first thing to get me online! I really appreciate the work you put into this!

      I had index.html inside the d3 folder and not inside the webserver folder :facepalm:

      Delete
    3. Awesome! Well done. Sometimes it's those first steps that can cause people to trip up and despair. Well done on persevering and for providing some great feedback!
      I really can't say enough good stuff about d3. It's a great framework. A little technical, but it needs that to be useful to follow on developers who can do great things. My aim is to help others who just need a bit of a hand to get to the point where they can have a play and if they like what they see, they can push on. I am really not that savvy, but I like what I see with d3. And there is a big bonus of having some seriously smart people involved. Good luck.

      Delete
  3. you can run `npm i -g http-server` and then run `http-server` wherever you save the files.

    ReplyDelete
    Replies
    1. Thanks Anthony. I remember seeing these instructions on one of the main d3 pages a while back, but I don't recall where. Is this valid for Windows users as well as Linux?

      Delete