Skip to content

Instantly share code, notes, and snippets.

@romsson
Last active January 25, 2019 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romsson/c598714fc24c4cadd89a22ea41cd1e4d to your computer and use it in GitHub Desktop.
Save romsson/c598714fc24c4cadd89a22ea41cd1e4d to your computer and use it in GitHub Desktop.
line chart with stocks.csv dataset
license: mit
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment