Skip to content

Instantly share code, notes, and snippets.

Last active January 13, 2022 23:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Simple d3.js graph with internal data
license: mit

This is a simple d3.js graph derived from this one and is used as an example to demonstrate the difference between getting data from an external source and declaring it internally.

It is aimed at providing some exposure to some d3.js functions and should be taken in context with the text of the book which can be downloaded for free from Leanpub.

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
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;
<!-- load the d3.js library -->
<script src=""></script>
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
var yAxis = d3.svg.axis().scale(y)
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(; })
.y(function(d) { return y(d.close); });
// Adds the svg canvas
var svg ="body")
.attr("width", width + margin.left + margin.right)
.attr("height", height + + margin.bottom)
"translate(" + margin.left + "," + + ")");
// Get the data
data = [
//d3.csv("data.csv", function(error, data) {
data.forEach(function(d) { = parseDate(;
d.close = +d.close;
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
// Add the valueline path.
.attr("class", "line")
.attr("d", valueline(data));
// Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
// Add the Y Axis
.attr("class", "y axis")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment