Public
Edited
May 7, 2023
Insert cell
Insert cell
base_bg_data = FileAttachment("games_detailed_info_trimmed.csv").csv({typed: true})
Insert cell
viewof games = aq.from(base_bg_data).filter(d => d.playingtime <= 300).view(5)
Insert cell
minPlayerCounts = uniqueValid(base_bg_data, d => d.minplayers, true);
Insert cell
viewof file = Inputs.file({label: "BoardGameGeek Collection Export", accept: ".csv", required: true})
Insert cell
user_data = file ? file.csv({typed: true}) : FileAttachment("collection.csv").csv({typed: true})
Insert cell
{
const scatter = zoomableScatterplot();
//const bar = barChart();
const histo = brushableHisto();

// update the scatterplot and XXXX when histo changes
//d3.select(histo).on('input', () => {
// scatter.update(histo.value);
//});

// update the scatterplot and histo when XXXX changes
// d3.select(scatter).on('input', () => {
// bar.update(scatter.value);
// histo_cyl.update(scatter.value);
// histo_displ.update(scatter.value);
// histo_hp.update(scatter.value);
// histo_acc.update(scatter.value);
// });
// initial state of charts
//scatter.update(scatter.value);
//bar.update(scatter.value);
//scatter.update(histo.value);

// build HTML table to place charts in
let table = html`<table><tr><td><br/>${scatter}</td><br/><td>${histo}</td></table>`;
return table;
}
Insert cell
function zoomableScatterplot() {
const leftMargin = 50, bottomMargin = 50, topMargin = 10;
const visWidth = scatter_sq - leftMargin, visHeight = scatter_sq - bottomMargin;

// the value for when there is no brush
const initialValue = games;

// set up
const xCol = "averageweight", xLabel = "Complexity";
const yCol = "average", yLabel = "Rating";

// function party
// zoom function directly used from https://observablehq.com/d/4669c7eb3b38d8d6
function zoomed({transform}) {
const zx = transform.rescaleX(x).interpolate(d3.interpolateRound);
const zy = transform.rescaleY(y).interpolate(d3.interpolateRound);
gDot.attr("transform", transform).attr("stroke-width", 5 / transform.k);
gx.call(xAxis, zx);
gy.call(yAxis, zy);
gGrid.call(grid, zx, zy);
}
const x = d3.scaleLinear()
.domain([0, d3.max(initialValue, d => d[xCol])]).nice()
.range([0, visWidth]);

const k = visHeight / visWidth;
const y = d3.scaleLinear()
.domain([0, d3.max(initialValue, d => d[yCol])]).nice()
.range([visHeight, 0]);

function xAxis(g, x){
return g.attr("transform", `translate(0,${visHeight})`)
.call(d3.axisTop(x).ticks(12))
.call(g => g.select(".domain").attr("display", "none"))
.append('text')
// add the label. inset temporarily while dealing with viewBox woes
.attr('x', visWidth / 2)
.attr('y', -20)
.attr('fill', 'black')
.attr('text-anchor', 'middle')
.attr('font-weight', 'bold')
.text(xLabel)
}

function yAxis(g, y){
return g.call(d3.axisRight(y).ticks(12 * k))
.call(g => g.select(".domain").attr("display", "none"))
// add the label. inset temporarily while dealing with viewBox woes
.append('text')
.attr("transform", "rotate(-90)") // now x, y flipped in terms of positioning
.attr("x", -1 * (visHeight / 2))
.attr("y", 20)
.attr('fill', 'black')
.attr('dominant-baseline', 'middle')
.attr('font-weight', 'bold')
.text(yLabel);
}

function grid(g, x, y) {return g
.attr("stroke", "currentColor")
.attr("stroke-opacity", 0.1)
.call(g => g
.selectAll(".x")
.data(x.ticks(10))
.join(
enter => enter.append("line").attr("class", "x").attr("y2", visHeight),
update => update,
exit => exit.remove()
)
.attr("x1", d => 0.5 + x(d))
.attr("x2", d => 0.5 + x(d)))
.call(g => g
.selectAll(".y")
.data(y.ticks(10 * k))
.join(
enter => enter.append("line").attr("class", "y").attr("x2", width),
update => update,
exit => exit.remove()
)
.attr("y1", d => 0.5 + y(d))
.attr("y2", d => 0.5 + y(d)))}

// zoom level & function trigger
const zoom = d3.zoom()
.extent([[0,0],[visWidth, visHeight]])
.on("zoom", zoomed);

const svg = d3.create("svg")
.attr("width", scatter_sq - leftMargin)
.attr("height", scatter_sq - bottomMargin);

const g = svg.append("g")
.attr("transform", `translate(${leftMargin}, ${topMargin})`);
const gDot = svg.append("g")
.attr("fill", "none")
.attr("stroke-linecap", "round");

const radius = 1;

gDot.selectAll("path")
.data(games)
.join("path")
.attr("d", d => `M${x(d[xCol])},${y(d[yCol])}h0`)
.attr("stroke", "#69b3a2")
.attr('stroke-width', 2)
.attr('r', radius);

const gGrid = svg.append("g");
const gx = svg.append("g");
const gy = svg.append("g");

svg.call(zoom).call(zoom.transform, d3.zoomIdentity);

/////////////////////////////////////////////////////////////////////////////////////
function update(data) {
// update the number of cars for each origin
const originCounts = d3.rollup(
data,
group => group.length,
d => d.Origin
);

// transition smoothly to look cute
const t = svg.transition()
.ease(d3.easeLinear)
.duration(200);

// draw bars
barsGroup.selectAll("rect")
.data(originCounts, ([origin, count]) => origin)
.join("rect")
.attr("fill", ([origin, count]) => carColor(origin))
.attr("height", y.bandwidth())
.attr("x", 0)
.attr("y", ([origin, count]) => y(origin))
.transition(t)
.attr("width", ([origin, count]) => x(count))
}

/////////////////////////////////////////////////////////////////////////////////////

return Object.assign(svg.node(), {
reset() {
svg.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity);
}, update
});
}
Insert cell
zoomableScatterplot()
Insert cell
brushableHisto()
Insert cell
function brushableHisto() {
// set up
const histoWidth = scatter_sq;
const num_hist = 4;
const histoHeight = (scatter_sq/num_hist)-(6*num_hist);

const svg = d3.create('svg')
.attr('width', histoWidth + margin.left + margin.right)
.attr('height', histoHeight + margin.top + margin.bottom);

const g = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);

// create x scale
const x = d3.scaleLinear()
.range([0, histoWidth])
.domain(d3.extent(games, d => d['playingtime'])).nice();
// https://www.d3-graph-gallery.com/graph/histogram_basic.html
// https://observablehq.com/@d3/d3-bin
const histogram = d3.bin()
.value(d => d['playingtime']) // specify the values used for the histogram
.domain(x.domain()); // domain is same as x-axis
const bins = histogram(games);
// create y scale
const y = d3.scaleLinear()
.range([histoHeight, 0])
.domain([0, d3.max(bins, d => d.length)]).nice(); // need to know bins first
// create and add axes
const xAxis = d3.axisBottom(x);
const xAxisGroup = g.append("g")
.attr("transform", `translate(0, ${histoHeight})`);
xAxisGroup.append("text")
.attr("x", 0)
.attr("y", 33)
.attr("fill", "black")
.attr("font-weight", "bold")
.attr("text-anchor", "start")
.text("Playtime");
xAxisGroup.call(xAxis);
const yAxis = d3.axisLeft(y).ticks(3);
const yAxisGroup = g.append("g").call(yAxis)
// add grid lines
.call(g => g.selectAll('.tick line')
.clone()
.attr('stroke', '#d3d3d3')
.attr('x1', 0)
.attr('x2', histoWidth))

// NEW: draw background gray bars
const bars = g.selectAll("rect")
.data(bins)
.join("rect")
.attr("fill", "lightgray")
.attr("x", d => x(d.x0) + 1)
.attr("width", d => x(d.x1) - x(d.x0)-1)
.attr("y", d => y(d.length))
.attr("height", d => histoHeight - y(d.length));
let barsGroup = g.append("g");

// BRUSHABILITY
const brush = d3.brushX()
.on('brush', onBrush)
.on('end', onEnd);

g.append('g')
.call(brush);

function onBrush(event) {console.log(event.selection);
const [x1, x2] = event.selection;

function isBrushed(d) {
//console.log(x(d['x0']) + " " + x(d['x1'])); // 10/10 would not have gotten this without page inspect
const cx0 = x(d['x0']);
const cx1 = x(d['x1']);
cx0 >= x1 && cx1 <= x2 ? console.log("Is brushed") : console.log("Is not brushed");
return cx0 >= x1 && cx1 <= x2;
}
bars.attr('fill', d => isBrushed(d) ? 'blue' : 'red');

// TODO: This will likely need a passthrough function that translates datapoints to bins. F.
svg.property('value', games.filter(isBrushed)).dispatch('input');
}

function onEnd(event){
// if the brush is cleared
if (event.selection === null) {
// reset the color of all of the dots
bars.attr('fill', 'gray');
svg.property('value', games).dispatch('input');
}
}


// NEW: added update() that updates bins and redraws bars
function update(data) {
// update bins
const histogram = d3.bin()
.value(d => d['playingtime']) // specify the values used for the histogram
.domain(x.domain()); // domain is same as x-axis
const bins = histogram(data);

// setup transition
const t = svg.transition()
.ease(d3.easeLinear) // easing examples at https://observablehq.com/@d3/easing-animations
.duration(200);
// draw bars
barsGroup.selectAll("rect")
.data(bins)
.join("rect")
.attr("fill", "steelblue")
.attr("x", d => x(d.x0) + 1)
.attr("width", d => x(d.x1) - x(d.x0) - 1)
.transition(t)
.attr("y", d => y(d.length))
.attr("height", d => histoHeight - y(d.length));
}
return Object.assign(svg.node(), { update });
}
Insert cell
margin = ({top: 10, right: 20, bottom: 50, left: 80})
Insert cell
scatter_sq = width * 0.45;
Insert cell
Insert cell
Insert cell
Insert cell
import { aq, op } from '@uwdata/arquero'
Insert cell
d3 = require("d3@7")
Insert cell
import {Swatches} from "@d3/color-legend"
Insert cell
import {uniqueValid} from "@jonfroehlich/data-utilities";
Insert cell
embed = require.alias({
"vega": "vega@5.21.0",
"vega-lite": "vega-lite@5.2.0"
})("vega-embed@6")
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