Public
Edited
May 23, 2020
1 fork
Insert cell
md`# Learning d3 - Bar Charts`
Insert cell
md`## simple bar chart
creating empty dom nodes from our data`
Insert cell
data = [ { "country": "UK", "population": 1000 }, { "country": "US", "population": 2000 }, { "country": "Malta", "population": 500 }, { "country": "France", "population": 700 }, ]
Insert cell
{
const svg = d3.create("svg");
svg.selectAll("rect").data(data).enter().append("rect");
return svg.node();
}
Insert cell
md`if we inspect the cell above we see that there is an svg DOM elememnt which contains three rect elements
Now let's style the rects so that we can see them`
Insert cell
{
const svg = d3.create("svg");
svg.selectAll("rect").data(data).enter().append("rect").attr("width", width).attr("height", 100);
return svg.node();
}
Insert cell
md`there are three rectangles being displayed but we only see one because they are overlapping each other
So now we can isolate each rectangle by individually setting their x,y and width
`
Insert cell
{
const height = 300;
const width = 600;
const xValue = d => d.population;
const yValue = d => d.country;
const margin = { top: 10, right: 20, bottom: 20, left: 70 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const svg = d3.create("svg").attr("height", height).attr("width", width);
const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);

const xScale = d3.scaleLinear().domain([0, d3.max(data, xValue)]).range([0, innerWidth]);
const yScale = d3.scaleBand().domain(data.map(yValue)).range([0, innerHeight]).padding(0.1);
g.append("g").call(d3.axisBottom(xScale)) // create new group element and add an X Axis to it
.attr("transform", `translate(0, ${innerHeight})`);
g.append("g").call(d3.axisLeft(yScale)); // create new group element and add a Y Axis to it

g.selectAll("rect").data(data).enter().append("rect")
.attr("y", d => yScale(yValue(d)))
.attr("width", d => xScale(xValue(d)))
.attr("height", yScale.bandwidth)
// .attr("fill", "steelblue");
return svg.node();
}
Insert cell
md`# Appendix`
Insert cell
d3 = require("d3@5");
Insert cell
html`<style>
rect { fill: steelblue; }
text { font-size: 1.4em; }
</style>`

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