Skip to content

Instantly share code, notes, and snippets.

@quizzicol
Created August 21, 2013 08:54
Show Gist options
  • Save quizzicol/6291978 to your computer and use it in GitHub Desktop.
Save quizzicol/6291978 to your computer and use it in GitHub Desktop.
A simple d3 example adding text elements, some data and a circle to a page.

A simple d3 example adding text elements, some data and a circle to a page.

var body = d3.select("body");
var text = body.append("text");
text.text("Hello!");
text.style("color","#f00");
text.attr("id","text");
var heading = d3.select("h1").style("color","#ff00ff");
var sub1 = d3.select("#sub1").style("color","#0f0");
var sub2 = d3.select(".sub2").style("color","#00f");
// add line breaks
sub1.append("br");
sub2.append("br");
text.append("br");
// make some data
var data = [];
for(var i=0;i<25;i++){
data.push(i);
}
// add div to display data in
var container = d3.select("body").append("div").attr("id","#container");
var data_text_selection = container.selectAll("text");
// this line creates a text element for each of the elements of the 'data' array created above and appends the relevant'data; value to the __data__ attribute of the text element
var data_text_elements = data_text_selection.data(data).enter().append("text");
// this function returns whatever is stored in the __data__ attibute.
data_text_elements.text(function(d){return d}).append("br");
data_text_elements.style("background-color", "#f00");
//remove text to continue the demonstration. Comment this line out to show the text elements.
container.selectAll("text").remove();
// add an SVG container
var svgContainer = container.append("svg");
svgContainer.attr("width", 300).attr("height", 200);
// add a circle to the SVG container
var circle = svgContainer.append("circle")
.attr("cx", 25)
.attr("cy", 25)
.attr("r", 20 )
.style("fill", '#f00');
circle.on("mousedown",free_definable_function);
function free_definable_function(){
console.log("Hello!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment