### Install Snowflake SDK Source: https://github.com/observablehq/notebook-kit/blob/main/docs/databases.html Installs the Snowflake SDK, an optional peer dependency for Notebook Kit. ```sh npm add snowflake-sdk ``` -------------------------------- ### Install Postgres Driver Source: https://github.com/observablehq/notebook-kit/blob/main/docs/databases.html Installs the Postgres driver, an optional peer dependency for Notebook Kit. ```sh npm add postgres ``` -------------------------------- ### Node.js Data Loader Cell Example Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html Example of a Node.js data loader cell. Writes 'hello world' to standard output. ```html ``` -------------------------------- ### D3 Force-Directed Graph Setup Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/force-directed-graph.html Initializes a D3 force simulation for nodes and links, applying forces for linking, charge, and centering. This is the core setup for the graph's physics. ```javascript const height = 600; const color = d3.scaleOrdinal(d3.schemeObservable10); // Make a copy prior to mutation. const links = data.links.map((d) => structuredClone(d)); const nodes = data.nodes.map((d) => structuredClone(d)); const simulation = d3.forceSimulation(nodes) .force("link", d3.forceLink(links).id((d) => d.id)) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 2, height / 2)); ``` -------------------------------- ### Notebook Kit Preview Command with Custom Template Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html Command to start the Notebook Kit preview server with a custom HTML page template. ```sh notebooks preview --root docs --template docs/custom.tmpl ``` -------------------------------- ### Python Data Loader Cell Example Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html Example of a Python data loader cell. Writes 'hello world' to standard output using sys.stdout. ```html ``` -------------------------------- ### Graphviz DOT Cell Example Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html Example of a DOT cell for generating Graphviz diagrams. The script defines a simple directed graph. ```html ``` -------------------------------- ### Observable JavaScript Cell Example Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html Example of an Observable JavaScript cell. Assigns a value to a variable 'foo'. ```html ``` -------------------------------- ### Markdown Cell Example Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html An example of a Markdown cell within an Observable Notebook, defined using a script tag with type 'text/markdown'. ```html ``` -------------------------------- ### Notebook Kit Build Command Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html Command to build a static site from notebooks, specifying the root directory and target HTML files. ```sh notebooks build --root docs -- docs/*.html ``` -------------------------------- ### TypeScript Cell Example Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html An example of a TypeScript cell within an Observable Notebook, defined using a script tag with type 'text/x-typescript'. ```html ``` -------------------------------- ### JavaScript Module Cell Example Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html An example of a JavaScript cell within an Observable Notebook, defined using a script tag with type 'module'. ```html ``` -------------------------------- ### Interactive Pie Chart Setup Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/pie-chart-update.html Sets up an interactive pie chart that updates based on user selection via radio buttons. Includes automatic data loading and animation. ```javascript const input = Inputs.radio( new Map([ ["Apples", "apples"], ["Oranges", "oranges"] ]), {label: "Series", value: "apples"} ); const series = view(input); const interval = d3.interval(() => { input.value = (input.value === "apples" ? "oranges" : "apples"); input.dispatchEvent(new Event("input", {bubbles: true})); }, 2000); const clear = () => interval.stop(); input.addEventListener("change", clear, {once: true}); invalidation.then(() => (clear(), input.removeEventListener("change", clear))); update(series); // side effect to animate the chart const data = display(d3.csvParse(`apples,oranges 53245,200 28479,200 19697,200 24037,200 40245,200`, d3.autoType)); ``` -------------------------------- ### Previewing Notebooks with Vite Source: https://github.com/observablehq/notebook-kit/blob/main/docs/index.html Run this command to preview your notebooks using Vite's development server. This allows for live previewing as you edit your notebook files. ```sh npm run docs:preview ``` -------------------------------- ### Expression Cell in Observable Notebooks Source: https://github.com/observablehq/notebook-kit/blob/main/docs/system-guide.html An example of an expression cell in JavaScript, which implicitly displays its evaluated value. ```javascript 1 + 2 ``` -------------------------------- ### Download Observable Notebook Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html Downloads and converts an Observable Notebook to a local HTML file. The output is redirected to a file. ```sh notebooks download https://observablehq.com/@d3/bar-chart > docs/bar-chart.html ``` -------------------------------- ### Albers-USA Projection Example Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/plot/albers-usa-projection.html Demonstrates the usage of the albers-usa projection for U.S.-centric maps. Requires Plot and TopoJSON libraries. ```javascript Plot.plot({ projection: "albers-usa", marks: [ Plot.geo(nation), Plot.geo(statemesh, {strokeOpacity: 0.2}) ] }) ``` ```javascript const us = await FileAttachment("data/us-counties-10m.json").json().then(display); const nation = topojson.feature(us, us.objects.nation); const statemesh = topojson.mesh(us, us.objects.states); ``` -------------------------------- ### Epicyclic Gearing Visualization Setup Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/epicyclic-gearing.html Initializes the D3.js SVG canvas and defines the gear components. This includes setting up the SVG dimensions, viewBox, stroke properties, and data for different gears (annulus, planets, sun). ```javascript const frameRadiusInput = Inputs.radio(new Map([ ["annulus", 0.5], ["planets", Infinity], ["sun", -0.1] ]), {key: "planets", label: "Fixed gear"}); const frameRadius = view(frameRadiusInput); const x = Math.sin(2 * Math.PI / 3); const y = Math.cos(2 * Math.PI / 3); const svg = d3.create("svg") .attr("width", 640) .attr("viewBox", [-0.53, -0.53, 1.06, 1.06]) .attr("stroke", "black") .attr("stroke-width", 1 / 640) .attr("style", "max-width: 100%; height: auto;"); const frame = svg.append("g"); const path = frame.selectAll() .data([ {fill: "#c6dbef", teeth: 80, radius: -0.5, origin: [0, 0], annulus: true}, {fill: "#6baed6", teeth: 16, radius: +0.1, origin: [0, 0]}, {fill: "#9ecae1", teeth: 32, radius: -0.2, origin: [0, -0.3]}, {fill: "#9ecae1", teeth: 32, radius: -0.2, origin: [-0.3 * x, -0.3 * y]}, {fill: "#9ecae1", teeth: 32, radius: -0.2, origin: [0.3 * x, -0.3 * y]} ]) .join("path") .attr("fill", (d) => d.fill) .attr("d", (d) => gear({...d, toothRadius: 0.008, holeRadius: 0.02})); display(svg.node()); ``` -------------------------------- ### Initialize Data and D3 Voronoi Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/voronoi-labels.html Sets up the data points and the D3 Voronoi diagram. The Voronoi diagram is initialized with bounds that extend beyond the plot area to ensure all points are covered. ```javascript const randomize = view(Inputs.button("Randomize")); const delaunay = d3.Delaunay.from(data); const voronoi = delaunay.voronoi([-1, -1, width + 1, height + 1]); ``` -------------------------------- ### Disjoint Force-Directed Graph Setup Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/disjoint-force-directed-graph.html Initializes a D3 force simulation for nodes and links, using positioning forces (forceX, forceY) suitable for disjoint graphs. Includes drag functionality for nodes. ```javascript const height = 680; const scale = d3.scaleOrdinal(d3.schemeCategory10); const color = (d) => scale(d.group); const links = data.links.map((d) => structuredClone(d)); const nodes = data.nodes.map((d) => structuredClone(d)); const simulation = d3.forceSimulation(nodes) .force("link", d3.forceLink(links).id((d) => d.id)) .force("charge", d3.forceManyBody()) .force("x", d3.forceX()) .force("y", d3.forceY()); const svg = d3.create("svg") .attr("viewBox", [-width / 2, -height / 2, width, height]); const link = svg.append("g") .attr("stroke", "#999") .attr("stroke-opacity", 0.6) .selectAll("line") .data(links) .join("line") .attr("stroke-width", (d) => Math.sqrt(d.value)); const node = svg.append("g") .attr("stroke", "#fff") .attr("stroke-width", 1.5) .selectAll("circle") .data(nodes) .join("circle") .attr("r", 5) .attr("fill", color) .call(drag(simulation)); node.append("title") .text((d) => d.id); simulation.on("tick", () => { link .attr("x1", (d) => d.source.x) .attr("y1", (d) => d.source.y) .attr("x2", (d) => d.target.x) .attr("y2", (d) => d.target.y); node .attr("cx", (d) => d.x) .attr("cy", (d) => d.y); }); invalidation.then(() => simulation.stop()); display(svg.node()); const data = FileAttachment("data/citations.json").json().then(display); ``` -------------------------------- ### Displaying Inputs and Getting Values with `view` Source: https://github.com/observablehq/notebook-kit/blob/main/docs/system-guide.html Shows how the `view` function displays an input and returns a generator for its current value. ```javascript const name = view(Inputs.text({label: "Name"})); `Hello, ${name || "anonymous"}!` ``` -------------------------------- ### Rendering Charts with Observable Plot Source: https://github.com/observablehq/notebook-kit/blob/main/docs/system-guide.html An example of rendering a line chart using Observable Plot, with grid lines enabled on the y-axis. ```javascript Plot.lineY(AMZN, {x: "Date", y: "Close"}).plot({y: {grid: true}}) ``` -------------------------------- ### Initialize D3 Scales and SVG for Temperature Trends Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/global-temperature-trends.html Sets up D3 scales for date and temperature values, defines a symmetric color scale for anomalies, and creates an SVG container. This is the initial setup for the visualization. ```javascript const width = 928; const height = 600; const marginTop = 20; const marginRight = 30; const marginBottom = 30; const marginLeft = 40; const x = d3.scaleUtc() .domain(d3.extent(data, (d) => d.date)) .range([marginLeft, width - marginRight]); const y = d3.scaleLinear() .domain(d3.extent(data, (d) => d.value)).nice() .range([height - marginBottom, marginTop]); const max = d3.max(data, (d) => Math.abs(d.value)); // Create a symmetric diverging color scale. const color = d3.scaleSequential( d3.interpolateRdBu ) .domain([-max, +max]); const svg = d3.create("svg") .attr("width", width) .attr("height", height) .attr("viewBox", [0, 0, width, height]) .attr("style", "max-width: 100%; height: auto;"); ``` -------------------------------- ### Connected Scatterplot Initialization Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/connected-scatterplot.html Initializes chart dimensions, margins, and helper functions for D3.js visualizations. This setup is common for most D3 charts. ```javascript const replay = view(Inputs.button("Replay")); replay; // Declare the chart dimensions and margins. const width = 928; const height = 720; const marginTop = 20; const marginRight = 30; const marginBottom = 30; const marginLeft = 40; // A helper to measure the length of an SVG path string. const length = (path) => d3.create("svg:path").attr("d", path).node().getTotalLength(); ``` -------------------------------- ### Get Root Rendering Element Source: https://github.com/observablehq/notebook-kit/blob/main/docs/kit.html Returns the root HTML element into which cells are rendered. This is typically the first
element or the . ```typescript root: HTMLElement ``` -------------------------------- ### Animated Treemap Setup Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/animated-treemap.html Initializes the animated treemap visualization. It sets up data scrubbing, defines dimensions, and prepares number parsing/formatting functions. This snippet is crucial for setting the stage for the animation. ```javascript const input = Scrubber(d3.range(data.keys.length), { delay: 2500, loop: false, format: (i) => data.keys[i] }); const index = view(input); const width = 928; const height = width; // This is normally zero, but could be non-zero if this cell is // re-evaluated after the animation plays. const initialIndex = input.value; // To allow the transition to be interrupted and resumed, we parse // the displayed text (the state population) to get the current // value at the start of each transition; parseNumber and // formatNumber must be symmetric. const parseNumber = (string) => +string.replace(/,/g, ""); const formatNumber = d3.format(",d"); ``` -------------------------------- ### Load and Prepare Data Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/plot/arealiney-custom-mark.html Loads CSV data from a file attachment and parses it with typed values. This is a prerequisite for using the 'arealineY' mark in the example. ```javascript const aapl = FileAttachment("data/AAPL.csv").csv({typed: true}).then(display); ``` -------------------------------- ### Initialize Interactive Scatterplot Tour Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/scatterplot-tour.html Sets up an interactive scatterplot with an animated tour that cycles through data clusters. It uses D3.js for zooming and transitions. The tour automatically advances every 2.5 seconds, stopping if the user interacts with the plot. ```javascript const input = Inputs.radio(new Map(transforms), {value: transforms[0][1]}); const transform = view(input); const interval = setInterval(() => { input.value = transforms[(transforms.findIndex(([ , t]) => t === input.value) + 1) % transforms.length][1]; input.dispatchEvent(new Event("input", {bubbles: true})); }, 2500); input.addEventListener("input", (event) => (event.isTrusted && clearInterval(interval))); invalidation.then(() => clearInterval(interval)); ``` -------------------------------- ### Initiate Zoom Transform Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/scatterplot-tour.html Applies an initial zoom transform to the SVG, typically used to set the starting view of the scatterplot, such as the 'Overview' state. ```javascript svg.call(zoom.transform, input.value); ``` -------------------------------- ### D3.js SVG Setup and Scales Source: https://github.com/observablehq/notebook-kit/blob/main/docs/ex/d3/psr-b1919-21.html Initializes SVG dimensions, margins, and overlap. Sets up D3.js scales for x, y, and z axes, mapping data domains to pixel ranges. ```javascript const width = 960; const height = 760; const marginTop = 60; const marginRight = 10; const marginBottom = 20; const marginLeft = 10; const overlap = 16; const x = d3.scaleLinear() .domain(d3.extent(pulsar, (d) => d[0])) .range([marginLeft, width - marginRight]); const z = d3.scalePoint() .domain(pulsar.map((d) => d[2])) .range([marginTop, height - marginBottom]); const y = d3.scaleLinear() .domain(d3.extent(pulsar, (d) => d[1])) .range([0, -overlap * z.step()]); ```