Built with blockbuilder.org
forked from romsson's block: bar chart axis color scale
license: mit |
Built with blockbuilder.org
forked from romsson's block: bar chart axis color scale
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
</style> | |
</head> | |
<body> | |
<script> | |
// 1. Create the SVG | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", 800) | |
.attr("height", 600) | |
// Scales | |
var x = d3.scaleBand() | |
.paddingInner(0.05) | |
.range([0, 500]); | |
var y = d3.scaleLinear() | |
.range([0, 100]); | |
var color = d3.scaleOrdinal(d3.schemeCategory20) | |
// 2. Load stocks data | |
// 0: {symbol: "MSFT", date: "Jan 2000", price: "39.81", value: 39.81} | |
d3.csv('https://raw.githubusercontent.com/LyonDataViz/MOS5.5-Dataviz/master/data/stocks.csv', function(error, raw) { | |
var symbols = []; | |
var data = [] | |
// Data pre-processing | |
raw.forEach(function(d, i) { | |
if(data[d.symbol] === "undefined") { | |
data[d.symbol] = []; | |
} | |
d.value = +d.price; | |
data[d.symbol].push(d); | |
symbols[d.symbol] = true | |
}) | |
symbols = d3.keys(symbols); | |
var xAxis = d3.axisBottom() | |
.scale(x); | |
var yAxis = d3.axisLeft() | |
.scale(y); | |
// Line generator | |
var line = d3.line().curve(d3.curveCardinal) | |
.x(function(d, i) { return x(i); }) | |
.y(function(d) { return 300 -y(d); }) | |
svg.selectAll(".line").data([data]).enter() | |
.append("path") | |
.attr("class", "line") | |
.attr("d", function(d) { return line(d); }) | |
.attr("stroke", "black") | |
svg.append('g') | |
.attr('transform', 'translate(15,' + 300 + ')') | |
.attr('class', 'x axis') | |
.call(xAxis); | |
svg.append('g') | |
.attr('transform', 'translate(15,' + 200 + ')') | |
.attr('class', 'y axis') | |
.call(yAxis); | |
}); | |
</script> | |
</body> |