# Canvas
HTML
<body>
<div id="vis"></div>
</body>
JavaScript
var vis = d3.select("#vis")
.append("svg") // This svg is where the actual visualization is later added by d3
# Enter-Update-Exit
- Select a group of elements
- Assign data to the group
var group = vis.selectAll("rect").data(rawdata)
`.data(rawData)`: Defaults to using index of the object in array as the key
`.data(rawData, function(d, i) { return d.id})`: uses `id` field of the object as the `key`
- Enter: Create new elements for data points not associated with any elements yet (set constant or initial attribute values
group.enter().append("rect")
.attr()
.style()
- Update: Set the attributes of all the elements based on the data
group.attr().style()
- Exit: Remove elements that don't have data anymore
group.exit().remove()
# Scales
# Linear scale
var xscale = d3.scale.linear()
.domain([min, max]) // value range of the dataset
.range( [minOut, maxOut]) // value range for the visualized graph
group.attr("x", function(d, i) {
return xscale(d.size);
})
You can use d3.min([])
, d3.max([])
and d3.extent([])
to get the min, max and the range respectively from an array of numbers.
If the values we exist within the objects of an object array, we can use the data.map
function as follows to return values of interest
var max = d3.max(
data.map(function (d) {return d.keyofinterest})
)
# Ordinal scale
var colorscale = d3.scale.category10()
.attr("fill", function(d, i) { return colorscale(d.type)})
There are things like category20()
, category20b()
etc
You don't want to use rainbow color palette if your data is not categorical and has some ordinality (eg. strongly agree, agree, neutral, etc)
# Axes
yaxisglyph = vis.append("g")
yaxis = d3.svg.axis()
.scale(yscale) // must be a numerical scale
.orient('left') // or 'right', 'top', or 'bottom'
.ticks(6) // number of ticks, default is 10
yaxisglyph.call(yaxis)
# Transitions
The transtion
, delay
and duration
functions facilitate the transitions.
D3 will automatically compute the intermediate values in between given the start and end values to create magical transitions
rect.attr("height", 0) // if this was original
rect.transition()
.delay(500) // in milliseconds, can be a function of data
.duration(200) // can be a function of data
.attr("height", 5)
.style("fill", "green")
# Interactivity
There on event listeners like in css like click
, mouseover
, mouseenter
, mouseout
, etc
rect.on("click", function(d) {
d.color = "blue";
redraw(rawData)
})