Created
October 17, 2017 13:32
-
-
Save ignorabilis/5b024e859c838e5ae2c1be7b9a7a230c to your computer and use it in GitHub Desktop.
Explore D3 - line chart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.3/d3.min.js"></script> | |
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// to view and play just use jsbin - copy the url and replace 'github' with 'jsbin' to instantly view the code in action | |
var w = 600; | |
var h = 200; | |
monthly_values = [{m: 1, sales: 9}, | |
{m: 2, sales: 4}, | |
{m: 3, sales: 22}, | |
{m: 4, sales: 17}, | |
{m: 5, sales: 19}, | |
{m: 6, sales: 21}, | |
{m: 7, sales: 44}, | |
{m: 8, sales: 99}, | |
{m: 9, sales: 20}, | |
{m: 10, sales: 4}, | |
{m: 11, sales: 3}, | |
{m: 12, sales: 7}]; | |
var svg = d3.select('body').append('svg') | |
.attrs({width: w, height: h}); | |
var line_fn = d3.line() | |
.x(function (d, i) { return d.m * w / (monthly_values.length + 1); }) | |
.y(function (d) { return h-d.sales; }) | |
.curve(d3.curveBundle); | |
var viz = svg.append('path') | |
.data([monthly_values]) | |
.attrs({ | |
"d": line_fn, | |
"stroke": "purple", | |
"stroke-width": 2, | |
"fill": "none" | |
}); | |
svg.selectAll("text") | |
.data(monthly_values) | |
.enter() | |
.append("text") | |
.text(function(d, i){ return d.sales; }) | |
.attrs({ | |
"text-anchor": "middle", | |
"x": function(d, i){ return d.m * w / (monthly_values.length + 1); }, | |
"y": function(d, i){ return h - d.sales - 15; }, | |
"fill": function(d, i) { return "#777777"; }, | |
"font-family": "sans-serif", | |
"font-size": 12, | |
"dy": "0.25em", | |
"font-weight": function (d, i) { if (d.m % 3 === 0){ | |
return "bold"; | |
} else { | |
return "normal"; | |
}} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment