Skip to content

Instantly share code, notes, and snippets.

@BruceHenry
Last active September 24, 2017 11:12
Show Gist options
  • Save BruceHenry/f52af1f1090fa3d6029467893478b02a to your computer and use it in GitHub Desktop.
Save BruceHenry/f52af1f1090fa3d6029467893478b02a to your computer and use it in GitHub Desktop.
Figure5.4 Scatterplots
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
.axis {
fill:none;
stroke:black;
stroke-width:3;
}
</style>
</head>
<body>
<script>
// Set the dimensions of the graph
var outerWidth = 300;
var outerHeight = 480;
var margin = { left: 30, top: 120, right: 30, bottom: 120 };
var innerWidth = outerWidth - margin.left - margin.right;
var innerHeight = outerHeight - margin.top - margin.bottom;
//Function to render the graph
function render(data){
var svg = d3.select("body").append("svg")
.attr("width", outerWidth)
.attr("height", outerHeight)
var circles = svg.selectAll("circle").data(data);
circles.enter().append("circle");
circles
.attr("cx", d=>margin.left+d.x)
.attr("cy",d=>margin.top+innerHeight-d.y)
.attr("r", d=>(typeof( d.r) !== 'undefined') ? d.r : 8)
.attr("fill",d=>(typeof(d.color) !== 'undefined') ? d.color : "#1E90FF");
var insideSvg = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xAxisG = insideSvg.append("g").attr("transform", "translate(0," + innerHeight + ")");
var yAxisG = insideSvg.append("g");
var xScale = d3.scale.ordinal().range([0, innerWidth]);
var yScale = d3.scale.ordinal().range([innerHeight,0 ]);
var xAxis = d3.svg.axis().scale(xScale).orient("bottom").outerTickSize(0);
var yAxis = d3.svg.axis().scale(yScale).orient("left").outerTickSize(0);
xAxisG.attr("class", "axis").call(xAxis);
yAxisG.attr("class", "axis").call(yAxis);
}
var data01 = [
{ x: 50, y: 100},
{ x:100, y: 150},
{ x:150, y: 50}
];
render(data01);
var data02 = [
{ x: 50, y: 100,color:"#ff4f1e"},
{ x:100, y: 150,color:"#ff4f1e"},
{ x:150, y: 50, color:"#1E90FF"}
];
render(data02);
var data03 = [
{ x: 50, y: 100,color:"#ff4f1e",r:8},
{ x:100, y: 150,color:"#ff4f1e",r:16},
{ x:150, y: 50, color:"#1E90FF",r:12}
];
render(data03);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment