Last active
September 26, 2017 14:33
-
-
Save mtandre/e82200d34d13285b287e6f2bf195e8ca to your computer and use it in GitHub Desktop.
Random scatter plots
This file contains 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 http-equiv="x-ua-compatible" content="ie=edge"> | |
<title>scatter plot</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
.axis path, .axis line {shape-rendering: crispEdges;} | |
text {font-family: monospace; font-size: 10px; fill: darkblue;} | |
</style> | |
</head> | |
<body> | |
<svg> | |
<defs> | |
<linearGradient id="grad" x1="0%" y1="0%" x2="0%" y2="100%" gradientUnits="userSpaceOnUse"> | |
<stop offset="0%" style="stop-color:steelblue;stop-opacity:1" /> | |
<stop offset="100%" style="stop-color:#fff;stop-opacity:1" /> | |
</linearGradient> | |
</defs> | |
</svg> | |
<script> | |
var w = 800, | |
h = 500, | |
padding = 40; | |
// 30 points of random 0 - 10 values | |
var dataset = []; | |
for (var i = 1; i < 31; i++) { | |
dataset.push([ | |
i, | |
Math.floor(Math.random() * 11) | |
]); | |
} | |
var svg = d3.select('svg') | |
.attr('width', w) | |
.attr('height', h); | |
var xScale = d3.scaleLinear() | |
.domain([0, d3.max(dataset, function(d){return d[0];})]) | |
.range([padding, w - padding]); | |
var yScale = d3.scaleLinear() | |
.domain([0, d3.max(dataset, function(d){return d[1];})]) | |
.range([h - padding, padding]); | |
// draw lines up to points | |
svg.selectAll('line') | |
.data(dataset) | |
.enter() | |
.append('line') | |
.attr('x1', function(d) { | |
return xScale(d[0]); | |
}) | |
.attr('x2', function(d) { | |
return xScale(d[0]); | |
}) | |
.attr('y1', h - padding) | |
.attr('y2', function(d) { | |
return yScale(d[1]); | |
}) | |
.attr('stroke', 'url(#grad)') | |
.attr('stroke-width', 1); | |
// draw points | |
svg.selectAll('circle') | |
.data(dataset) | |
.enter() | |
.append('circle') | |
.attr('cx', function(d){ | |
return xScale(d[0]); | |
}) | |
.attr('cy', function(d){ | |
return yScale(d[1]); | |
}) | |
.attr('r', 3) | |
.attr('fill', 'dodgerblue'); | |
var xAxis = d3.axisBottom() | |
.scale(xScale) | |
.ticks(30); | |
svg.append('g') | |
.attr('class', 'axis') | |
.attr('transform', 'translate(0,'+(h - padding)+')') | |
.call(xAxis); | |
var yAxis = d3.axisLeft() | |
.scale(yScale) | |
.ticks(10); | |
svg.append('g') | |
.attr('class', 'axis') | |
.attr('transform', 'translate('+ padding +',0)') | |
.call(yAxis); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment