Published
Edited
May 14, 2020
Fork of Barcode Plot
1 fork
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

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

svg.append("g")
.call(yAxis);
var myColor = d3.scaleDiverging(t => d3.interpolateRdBu(1 - t)).domain([-1, 0, 1])
.interpolator(d3.interpolateRdBu);

svg.append("g")
.attr("stroke-width", 3)
.attr("pointer-events", "all")
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", d => x(d.value))
.attr("y", d => y(d.row))
.attr("width", 20.0)
.attr("height", y.bandwidth())
.attr("fill", function(d){return myColor(d.color)})
.on('mousemove', function (d) {
d3.select(this).transition()
.duration('50')
.attr('opacity', '0.5')
.text(d.row);
dot.attr("transform", `translate(${x(d.value)},${y(d.row)})`);
dot.attr("display", null);
dot.select('text').text(d.row + " | " + d.spaces);
})
.on('mouseout', function (d) {
d3.select(this).transition()
.duration('50')
.attr('opacity', '1');
dot.attr("display", "none");
});
const dot = svg.append("g")
.attr("display", "none");

dot.append("circle")
.attr("r", 0.5);

dot.append("text")
.attr("font-family", "sans-serif")
.attr("font-size", 30)
.attr("text-anchor", "middle");

return svg.node();
}
Insert cell
data = {
const data = d3.csvParse(await FileAttachment("us-population-state-age.csv").text(), d3.autoType);
const ages = data.columns.slice(1);
var i = 0
for (const d of data) {
d.total = i;
i = i + 0.01
}
var j = 0
for (const d of data) {
d.space = j
j = j + 1
}
return ages.flatMap(age => data.map(d => ({row: age, spaces: d.space, value: d.total, color: d.total - 0.3})));
}
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data, d => d.value))
.range([margin.left+10, width - margin.right])
Insert cell
y = d3.scaleBand()
.domain(data.map(d => d.row))
.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(null, "%"))
// .call(g => g.selectAll(".tick line").clone().attr("stroke-opacity", 0.1).attr("y2", height - margin.bottom - margin.top))
// .call(g => g.selectAll(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.selectAll(".tick line").clone().attr("stroke-opacity", 0.1).attr("x2", width - margin.right - margin.left)).attr("font-size", 14)
.call(g => g.selectAll(".domain").remove())
Insert cell
height = 400
Insert cell
margin = ({top: 20, right: 10, bottom: 10, left: 40})
Insert cell
d3 = require("d3@5")
Insert cell
import {legend} from "@d3/color-legend"
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