Skip to content

Instantly share code, notes, and snippets.

@dhoboy
Created January 14, 2015 01:46
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 dhoboy/39513735422b08a1cc3f to your computer and use it in GitHub Desktop.
Save dhoboy/39513735422b08a1cc3f to your computer and use it in GitHub Desktop.
More interesting Scatterplot
<html>
<head>
<script src="http://d3js.org/d3.v3.js"></script>
<style>
.axis path,
.axis line {
fill: none;
stroke: green;
stroke-width: 3px;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
fill: #743403;
}
</style>
</head>
<body>
<script>
// size of svg
var h = 500;
var w = 500;
var padding = 30;
// generate random data (real data coming soon :)
var dataset = [];
var xRange = Math.random() * 1000;
var yRange = Math.random() * 1000;
for(var i = 0; i < 50; i++) {
dataset.push([Math.round(Math.random() * xRange), Math.round(Math.random() * yRange)]);
}
// make scales
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[0]; })])
.range([padding, w - padding]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([h - padding, padding]);
var rScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([2,5]);
var colorScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[0]; })])
.range(["yellow","purple"]);
// append the svg
var svg = d3.select("body")
.append("svg")
.attr("height", h)
.attr("width", w);
// plot the data
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", function(d){
return rScale(d[1]);
})
.attr("fill", function(d){
return colorScale(d[0]);
})
// add the axes
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(5);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
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