Skip to content

Instantly share code, notes, and snippets.

@benjchristensen
Created August 9, 2011 05:38
Show Gist options
  • Save benjchristensen/1133472 to your computer and use it in GitHub Desktop.
Save benjchristensen/1133472 to your computer and use it in GitHub Desktop.
Simple Sparkline using SVG Path and d3.js
<html>
<head>
<title>Simple Sparkline using SVG Path and d3.js</title>
<script src="http://mbostock.github.com/d3/d3.v2.js"></script>
<style>
/* tell the SVG path to be a thin blue line without any area fill */
path {
stroke: steelblue;
stroke-width: 1;
fill: none;
}
</style>
</head>
<body>
<div id="graph" class="aGraph" style="position:absolute;top:0px;left:0; float:left; width:300px; height:60px;"></div>
<script>
// create an SVG element inside the #graph div that fills 100% of the div
var graph = d3.select("#graph").append("svg:svg").attr("width", "100%").attr("height", "100%");
// create a simple data array that we'll plot with a line (this array represents only the Y values, X will just be the index location)
var data = [3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 3, 6, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9];
// X scale will fit values from 0-10 within pixels 0-100
var x = d3.scale.linear().domain([0, 10]).range([0, 50]);
// Y scale will fit values from 0-10 within pixels 0-100
var y = d3.scale.linear().domain([0, 10]).range([0, 30]);
// create a line object that represents the SVN line we're creating
var line = d3.svg.line()
// assign the X function to plot our line as we wish
.x(function(d,i) {
// verbose logging to show what's actually being done
console.log('Plotting X value for data point: ' + d + ' using index: ' + i + ' to be at: ' + x(i) + ' using our xScale.');
// return the X coordinate where we want to plot this datapoint
return x(i);
})
.y(function(d) {
// verbose logging to show what's actually being done
console.log('Plotting Y value for data point: ' + d + ' to be at: ' + y(d) + " using our yScale.");
// return the Y coordinate where we want to plot this datapoint
return y(d);
})
// display the line by appending an svg:path element with the data line we created above
graph.append("svg:path").attr("d", line(data));
</script>
</body>
</html>
@kitmonisit
Copy link

The d3.js script link needs to be updated.

@benjchristensen
Copy link
Author

Updated the d3.js link to http://mbostock.github.com/d3/d3.v2.js

@misterdai
Copy link

Is it me or does this plot the sparkline upsidedown?

@warrendunlop
Copy link

@misterdai upsidedown for me too. Would be great if this one auto-calculated domain and range based on the data set.

@SamMorrowDrums
Copy link

Height should have been second argument to range, that's why

var y = d3.scale.linear().domain([0, 10]).range([30, 0]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment