Published
Edited
Feb 12, 2020
3 forks
10 stars
Insert cell
Insert cell
Insert cell
Insert cell
DOM // expand and get familiar with the DOM elements
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
const D3Svg = d3.selectAll('svg').remove() // Without this, D3 just keeps appending new svg each time, try commenting and running this.

//D3 selection of class parent-container (which continues down the method chain...)
const d3Selection = d3.select('.parent-container')
.append('svg') // append svg element with d3 object
.attr('width', 100) // add attribute width to svg
.attr('height', 100) // add attribute height to svg

// Appending CIRCLE (NOT using method-chaining. Which do you prefer?)
const d3AppendedCircle = d3Selection.append('circle') // appending circle element
d3AppendedCircle.attr('cx', 50) // add attribute x-axis coordinate of the center of the circle.
d3AppendedCircle.attr('cy', 50) // add attribute y-axis coordinate of the center of the circle.
d3AppendedCircle.attr('r', 25) // add attribute radius to circle
d3AppendedCircle.attr('fill', 'purple') //fill circle with described colour.
return D3Svg
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
const D3DataConnection = d3.select(p).selectAll("p")
.data(ArrayofData)
.enter()
.append("p")
.text(function(d) {
return "I can count up to " + d;
})
.style("color", function(d) {
if (d > 15) { //Threshold of 15
return "red"; // paragraph appears in red if value is greater than 15
} else {
return "black"; // paragraph appears in black if value is less than or equal to 15
}
})
return D3DataConnection
}
Insert cell
Insert cell
Insert cell
{
const width = 500 //width of svg
const height = 250 //height of svg
//Another direct method to create svg is DOM.svg(specific to Observables)
const svg = d3.select(DOM.svg(width, height))
const ArrayofData = [50,90, 120,250,200,150,100,50,10,40,80,60,40,70,50,90, 120,60,40,70,50,60,40,70]
svg.selectAll('rect')
.data(ArrayofData) //connect ArrayofData with DOM <rect/> elements
.enter() // returns the portion of the data which is new ("entering") and not yet bound to DOM elements
.append('rect') // for each data value, append a <rect/> to selected svg
.attr('x', (d, itemsIndexInArray) => itemsIndexInArray * 20)// For each, set x attr
.attr('y', d => height - d) // for each, set y attr
.attr('width', 15) // for each, set width attribute
.attr('height', arrayItemTypicallyNamed_d => arrayItemTypicallyNamed_d)
.attr('fill', 'purple')
// Once we append the visualization elments to it, we return the DOM element for Observable to display above.
return svg.node()
}
Insert cell
Insert cell
Insert cell
d3 = require('d3@5')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more