Published
Edited
Oct 17, 2019
2 forks
Importers
Insert cell
md`# Drawing a chart`
Insert cell
d3 = require("d3")
Insert cell
// import basbeall player salary information
raw = d3.tsv("https://gist.githubusercontent.com/lathropd/0d63302f6c3c1014f2cd3846a23967a8/raw/9e7f666b7a2a83fb6d8e444215d7c46a0d60a62b/baseball.tsv")
Insert cell
// this is a function that receives a list of players and returns a summary of them
function summarize(players) {
let count = players.length;
let pay = players.map(d => +d["Average Pay"]);
let mean = d3.mean(pay);

return { count, mean };
}
Insert cell
data = d3
.nest()
.key(d => d.POS)
.rollup(summarize)
.entries(raw)
.map(d => {
return {
position: d.key,
"number of players": d.value.count,
"average annual pay": d.value.mean
};
})
Insert cell
d3.format(".10p")(0.1)
Insert cell
height = width / 2
Insert cell
max = d3.max(data, d => d["average annual pay"])
Insert cell
x = d3
.scaleLinear()
.domain([0, max])
.range([0, width - marginLeft - marginRight])
Insert cell
y = d3
.scaleBand()
.domain(data.map(d => d.position))
.range([marginTop, height - marginBottom])
Insert cell
marginTop = 50
Insert cell
marginLeft = 50
Insert cell
marginRight = 50
Insert cell
marginBottom = 50
Insert cell
chart = {
// create svg for chart
let svg = d3.create("svg");

// set height and width
svg.attr("height", height).attr("width", width);

// create bars based on data array
svg
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", 50)
.attr("y", d => y(d.position))
.attr("width", d => x(d["average annual pay"]))
.attr("height", 20)
.style("fill", "red");

// add x axis at top, move axis in and down
svg
.append("g")
.call(d3.axisTop(x))
.attr("transform", "translate(50,45)"); // left margin 50, top margin 50 less 5 px

// create y axis at ledt, move axis in
svg
.append("g")
.call(d3.axisLeft(y))
.attr("transform", "translate(45,0)"); // left margin 50 less 5 p

// return svg element
return svg.node();
}
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