Published
Edited
Mar 31, 2021
1 fork
Insert cell
md`# D3 practice, 2021-03-31
Our task today:
`
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
w = 900
Insert cell
h = 400
Insert cell
margin = ({top: 10, right: 10, bottom: 10, left: 10})
Insert cell
svg = d3.select("#demo")
.append("svg")
.attr("width", w)
.attr("height", h)
.style("background-color", "pink")
Insert cell
Insert cell
dataset = {
let dataset = [];
for (let i = 0; i < numBar; i++) {
let randomNum = Math.random() * 1000;
dataset.push(randomNum)
}
return dataset;
}
Insert cell
Insert cell
Insert cell
xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.range([0, w])
.paddingInner(0.05)
Insert cell
yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)])
.range([h, 0]);
Insert cell
Insert cell
svg.selectAll("rect")
.data(dataset)
.join("rect")
.attr("x", function(d, i) {return xScale(i)}) // (d, i) => xScale(i)
.attr("y", d => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => h - yScale(d))
.style("fill", colorBar)
Insert cell
md`
## Be a good (event) listener!
`
Insert cell
d3.select(button) // Don't use "button"
.on ("click", function(){
let dataset = [];
for (let i = 0; i < numBar; i++) {
let randomNum = Math.random() * 1000;
dataset.push(randomNum)
}
xScale.domain(d3.range(dataset.length));
yScale.domain([0, d3.max(dataset)]);

svg.selectAll("rect")
.data(dataset)
.transition()
.delay((d, i) => i / dataset.length * 1000)
.ease(d3.easeLinear)
.duration(1000) //miliseconds
.attr("x", function(d, i) {return xScale(i)}) // (d, i) => xScale(i)
.attr("y", d => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => h - yScale(d));
})
Insert cell
viewof numBar = Range([1, 25], {value: 18, step: 1, label: "number of bars:"})
Insert cell
viewof colorBar = color({
value: "#4682b4",
title: "Color of bars",
description: "You can the color of bars here"
})
Insert cell
button = html`<button>Click for new data</button>`
Insert cell
chart = html`<div id = "demo"></div>`
Insert cell
d3 = require("d3@6")
Insert cell
import {Range} from "@observablehq/inputs"
Insert cell
import {color} from "@jashkenas/inputs"
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