Skip to content

Instantly share code, notes, and snippets.

View svg-example.html
<svg width="400" height="60">
<rect x="0" y="0" width="50" height="50" fill="green"></rect>
<circle cx="90" cy="25" r="25" fill="red"></circle>
<ellipse cx="145" cy="25" rx="15" ry="25" fill="grey"></ellipse>
<line x1="185" y1="5" x2="230" y2="40" stroke="blue" stroke-width="5"></line>
<text x="260" y="25" font-size="20px" fill="orange">Hello World</text>
</svg>
View simple-circle.js
d3.select("#canvas")
.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 5)
.attr("fill", "grey");
View loop-append.js
for(var i = 0; i < data0.length; i++) {
d3.select("#canvas")
.append("circle")
.attr("cx", data0[i].gpa)
.attr("cy", data0[i].height)
.attr("r", 5)
.attr("fill", "grey");
}
View data-join.js
var circles = d3.select("#canvas").selectAll("circle")
.data(data0);
circles.enter().append("circle")
.attr("cx", function(d, i){ return 25 + (50 * i); })
.attr("cy", function(d, i){ return 25 + (50 * i); })
.attr("r", 5)
.attr("fill", "grey");
View scales-demo.js
var x = d3.scaleLinear()
.domain([d3.min(data0, function(d){ return d.gpa; }) / 1.05,
d3.max(data0, function(d){ return d.gpa; }) * 1.05])
.range([0, 800]);
var y = d3.scaleLinear()
.domain([d3.min(data0, function(d){ return d.height; }) / 1.05,
d3.max(data0, function(d){ return d.height; }) * 1.05])
.range([500, 0]);
View circles-scales.js
var circles = d3.select("#canvas").selectAll("circle")
.data(data0);
circles.enter()
.append("circle")
.attr("cx", function(d){ return x(d.gpa) })
.attr("cy", function(d){ return y(d.height) })
.attr("r", 5)
.attr("fill", "grey");
View margin-convention.js
var svg = d3.select("#canvas");
var margin = {top: 10, right: 10, bottom: 50, left: 50};
var width = +svg.attr("width") - margin.left - margin.right;
var height = +svg.attr("height") - margin.top - margin.bottom;
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
View axes-labels.js
// Axes
var xAxisCall = d3.axisBottom(x)
var xAxis = g.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(" + 0 + "," + height + ")")
.call(xAxisCall);
var yAxisCall = d3.axisLeft(y)
var yAxis = g.append("g")
.attr("class", "y-axis")
View d3-interval.js
var flag = true;
// Run this code every second...
d3.interval(function(){
// Flick between our two data arrays
data = flag ? data0 : data1;
// Update our chart with new data
update(data);
View d3-update.js
// Scales
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
// Axes
var xAxisCall = d3.axisBottom(x)
var xAxis = g.append("g")
.attr("class", "x-axis")