Skip to content

Instantly share code, notes, and snippets.

@sakamies
Created July 23, 2015 19:41
Show Gist options
  • Save sakamies/1bf1e7773e783a1bd1b8 to your computer and use it in GitHub Desktop.
Save sakamies/1bf1e7773e783a1bd1b8 to your computer and use it in GitHub Desktop.
Trivial SVG graph
<svg id="example" class="graph" preserveaspectratio="none" width="200" height="100"><path class="line"/></svg>
function graph (selector, data) {
var svg = document.querySelector(selector);
var line = svg.querySelector('.line');
var numOfPoints = data.x.length;
var xmin = Math.min.apply(null, data.x);
var xmax = Math.max.apply(null, data.x);
var ymin = Math.min.apply(null, data.y);
var ymax = Math.max.apply(null, data.y);
var xrange = xmax - xmin;
var yrange = ymax - ymin;
var path = 'M' + xmin + ',' + ymin + ' ';
for (var i = 0; i < numOfPoints; i++) {
path += 'L' + data.x[i] + ',' + data.y[i] + ' ';
};
path += 'L' + xmax + ',' + ymin + ' ';
path += ' Z';
var viewBox = [xmin, ymin, xrange, yrange].join(' ');
//transform coordinate system start from bottom left
var transform = 'translate(0, '+(ymin*2+yrange)+') scale(1,-1)'
svg.setAttribute('viewBox', viewBox);
line.setAttribute('d', path);
line.setAttribute('transform', transform);
}
var data = {
x: [
9211,
9221,
9231,
9241,
9251,
9261,
9271,
9281,
9291,
],
y: [
12.4,
11.6,
11.4,
0,
-3,
9.1,
23.0,
10.6,
19.4
]
}
graph('#example', data);
/*a bit of a reset*/
body,
html,
.graph {
display: block;
width: 100%;
height: 100%;
margin: 0;
}
/*set a nice color*/
body {
color: #666;
}
/*inherit color*/
.line {
fill: currentColor;
}

Trivial SVG graph

Trying to find the simplest way to make an SVG graph. No features really, just drawing a graph when given some data for x & y axes, with minimal manipulation and code.

A Pen by Ville V. Vanninen on CodePen.

License.

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