D3-js[Data handling]
Local server hosting
Open a new terminal in Mac
cd ~/Desktop/project-folder
python -m SimpleHTTPServer 8888 &.filename
Chaining
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "utf-8">
<title> D3 Page Template</title>
<script type="text/javascript" src="d3.js"></script>
</head>
<body>
<script type="text/javascript">
d3.select("body").append("p").text("New paragraph!");
</script>
</body>
</html>
d3: Refer the D3 object.
.select("body"): Give the select() method a CSS selector as input
append("p"): empty p paragraph is appended to the body.
.text("New paragraph!")
Handoff: D3 methods return a selection (So it uses chaining)
Without chaining we can also re-paragraph above code.
var body = d3.select("body");
var p = body.append("p");
p.text("New paragraph!");
Binding data
d3.csv("food.csv", function(data) {
console.log(data);
});
csv(): the path, call back function
When the call back function is called, the csv file is already imported. Every value in csv is stored as a string, even the number. So converting is needed. While the csv fild is loaded, the rest of a code is executed so assigning global variable would be helpful.
var rowConverter = function(d) {
return {
Food: d.Food, //No conversion
Deliciousness: parseFloat(d.Deliciousness)
};
}
d3.csv("food.csv", rowConverter, function(data) {
console.log(data);
});
Selection
var dataset = [5,10,15,20,25];
d3.select("body").selectAll("p")
.data(dataset)
.enter()
.append("p")
.text("New paragraph!")
//.text(function(d) { return d; });
We have to select elements that don't yet exist. The magical method is "enter"
d3.select("body"): Finds the body in the DOM
.selectAll("p"): Selects all paragraphs in the DOM. This returns an empty selection because none exist yet.
.data(dataset): Counts and parses our data values.
enter(): Creates a new placeholder element
.append("p"): appends a p element
.text("New paragraph!"): inserts a text value into p
If we use .text(function(d) { return d; }); it populates the contents of each paragraph from our data.
Functioning
function(input_value) {
//Calculate something here
return output_value;
}
Div and Attr
var dataset = [5,10,15,20,25];
<div style = "display: inline-block;
width: 20px;
height: 75px;
background-color: teal;"></div>
div needs to be assigned the bar class. To add a class to an element, we use the attr() method. (not style()) style() applies CSS styles directly to an element.
Attribute
Value
class
caption
id
country
src
logo.png
width
100px
alt
Logo
To assign a class of bar we can use: .attr("class","bar")
Classes
Element's class is stored as an HTML attribute.
.classed("bar", true)
// If true->false, it removesthe class of bar.
Last updated
Was this helpful?