Published unlisted
Edited
Nov 2, 2021
Insert cell
# Interactive colour legend for provinces
Insert cell
Insert cell
viewof selection2 = {
// set up

const svg = d3.create('svg')
.attr('width', 1000)
.attr('height', visHeight + margin.top + margin.bottom);

const rowHeight = 20;
const fontSize = 15;


const rows = svg.selectAll('g')
.data(Provinces)
.join('g')
// position the group for each row of the legend
.attr('transform', (d, i) => `translate(755, ${i * rowHeight + 5})`);

// add colored square to each row
rows.append('rect')
.attr('width', fontSize)
.attr('height', fontSize)
.attr('stroke-width', 2)
.attr('stroke', d => carColor(d))
.attr('fill', d => carColor(d))
.on('click', onclick);

// add label to each row
rows.append('text')
.attr('font-size', fontSize)
.attr('x', rowHeight)
.attr('y', fontSize / 2)
.attr('font-family', 'sans-serif')
.attr('dominant-baseline', 'middle')
.text(d => d);

// Track which origins are selected in the legend.
// This is a map from car origin to a boolean for
// whether or not it the origin is selected.
// To start, all origins are selected.
const selected = new Map(Provinces.map(d => [d, true]));

function onclick(event, d) {
const isSelected = selected.get(d);

// this refers to the square that was clicked
const square = d3.select(this);
// toggle the square
square.attr('fill', d => isSelected ? 'white' : carColor(d));
selected.set(d, !isSelected);
svg.property('value', selected).dispatch('input');
}
svg.property('value', selected).dispatch('input');

const g = svg.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
// axes
g.append("g").call(xAxis, x, 'time');
g.append("g").call(yAxis, y, 'numconf');
// draw points
g.selectAll('circle')
// filter data to only contain selected car origins
.data(data1.filter(d => selections.get(d.prname)))
.join('circle')
.attr('cx', d => x(d.date))
.attr('cy', d => y(d.numconf))
.attr('fill', d => carColor(d.prname))
.attr('opacity', 1)
.attr('r', 3);

return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
carColor = d3.scaleOrdinal()
.domain(Provinces)
.range(["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf", "#00ff00", "#333333", "#ffff00", "#dcedc1", "#b6fcd5"]);
Insert cell
Insert cell
visWidth = 400
Insert cell
visHeight = 400
Insert cell
Insert cell
Insert cell
Insert cell
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