Published
Edited
May 16, 2021
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
Insert cell
datasets = require("vega-datasets")
Insert cell
gapminder = datasets["gapminder.json"]()
Insert cell
gapminder2005_top10 = gapminder.filter(d => d.year === 2005).sort((a, b) => b.pop - a.pop).slice(0,10)
Insert cell
Insert cell
margin = ({top: 20, right: 20, bottom: 60, left:100})
Insert cell
h = 600 - margin.top - margin.bottom
Insert cell
w = width - margin.left - margin.right
Insert cell
Insert cell
xScale = d3.scaleLinear()
.domain([0, d3.max(gapminder2005_top10, d => d.pop)])
.range([0, w])
Insert cell
yScale = d3.scaleBand()
.domain(gapminder2005_top10.map(d => d.country))
.range([0, h])
.padding(1)
Insert cell
Insert cell
Insert cell
viewof replay = html`<button>Replay`
Insert cell
{
replay;
const container = d3.create("svg")
.attr("height", h + margin.top + margin.bottom)
.attr("width", width)

// to make sure the chart is within the margins
const chart = container.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")

// call x-axis
chart.append("g")
.attr("transform", "translate(0," + h + ")")
.call(d3.axisBottom(xScale))
.selectAll("text")
.attr("transform", "rotate(-45)translate(-5,0)")
.attr("text-anchor", "end")
.style("font-size", "10px")
.style("font-family", "Helvetica Neue, Arial")


// call y-axis
chart.append("g")
.call(d3.axisLeft(yScale))
.selectAll("text")
.style("font-size", "12px")
.style("font-family", "Helvetica Neue, Arial")

// lines
chart.selectAll("myline")
.data(gapminder2005_top10)
.enter()
.append("line")
.attr("x1", xScale(0))
.attr("x2", xScale(0))
.attr("y1", d => yScale(d.country))
.attr("y2", d => yScale(d.country))
.attr("stroke", "steelblue")
// circles
chart.selectAll("mycircle")
.data(gapminder2005_top10)
.enter()
.append("circle")
.attr("cx", xScale(0))
.attr("cy", d => yScale(d.country))
.attr("r", "6")
.attr("fill", "turquoise")

// transition
chart.selectAll("line")
.transition()
.duration(2000)
.attr("x1", d => xScale(d.pop))
chart.selectAll("circle")
.transition()
.duration(2000)
.attr("cx", d => xScale(d.pop))
.attr("r", "8")
return container.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