Published
Edited
May 9, 2020
2 forks
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [-10, 0, width, height]);
svg.append("g")
//.attr("fill", "#1DA1F2")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", x(0))
.attr("y", (d, i) => y(i))
.attr("width", d => x(d.value) - x(0))
.attr("height", y.bandwidth())
.attr("fill", d => color(d.name));
svg.append("g")
.attr("fill", "white")
.attr("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("font-size", 20)
.selectAll("text")
.data(data)
.join("text")
.attr("x", d => x(d.value) - 4)
.attr("y", (d, i) => y(i) + y.bandwidth() / 2)
.attr("margin.right","0.3em")
.attr("dy", "0.25em")
.attr("dx", "0.1em")
.text(d => format(d.value));

svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis)
.attr("font-size", 30);

return svg.node();
}
Insert cell
color = {
const color = d3.scaleOrdinal(d3.quantize(d3.interpolateHcl("#FFAD05", "#1DA1F2"), 4));
return name => color(name.replace(/ .*/, ""));
}
Insert cell
data = Object.assign(d3.csvParse(await FileAttachment("q10_test.csv").text(), ({letter, frequency}) => ({name: letter, value: +frequency})).sort((a, b) => d3.descending(a.value, b.value)))
Insert cell
format = x.tickFormat(10, data.format)
Insert cell
x = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleBand()
.domain(d3.range(data.length))
.rangeRound([margin.top, height - margin.bottom])
.padding(0.1)
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${margin.top})`)
.call(d3.axisTop(x).ticks(width / 80, data.format))
.call(g => g.select(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickFormat(i => data[i].name).tickSizeOuter(0))
Insert cell
barHeight = 60
Insert cell
height = Math.ceil((data.length + 0.1) * barHeight) + margin.top + margin.bottom
Insert cell
margin = ({top: 30, right: 30, bottom: 10, left: 50})
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