Public
Edited
Aug 1, 2023
40 forks
7 stars
Revenue by music format, 1973–2018New Zealand tourists, 1921–2018Sea ice extent, 1978–2017U.S. population by State, 1790–1990Hertzsprung–Russell diagramSpilhaus shoreline mapWalmart’s growthInequality in American citiesU.S. state choroplethWorld choroplethScatterplot matrixLine chart, multiple seriesLine chart with tooltipTreemapBar chart transitionsBand chartCancer survival ratesSlope chartDifference chartDiverging bar chartDiverging stacked bar chartScatterplotSpike mapBubble mapBox plotPSR B1919+21Normalized stacked area chartDirected chord diagramChord dependency diagramVolcano contoursRadial area chartRadial stacked bar chart, sortedRadial stacked bar chartHorizon chartSunburstStreamgraphTidy treeCluster treeRadial cluster treeBeeswarmIciclePie chartCircle packingRadial tidy treeHorizontal bar chartBubble chartStacked area chartLine chart, percent changeSankey diagram
Index chart
Disjoint force-directed graphForce-directed graphHistogramBollinger bandsCandlestick chartConnected scatterplotDot plotGrouped bar chartStacked bar chart, normalizedStacked bar chart, horizontalStacked bar chartDonut chartLine chart, missing dataArea chart with missing dataArea chartChoroplethCalendarLine chartColor SchemesWord cloudd3.packEncloseNon-contiguous cartogramStar mapSolar pathSolar TerminatorWorld airports VoronoiU.S. airports VoronoiGeoTIFF contours IIVector fieldRaster & vectorClipped map tilesVector tilesRaster tilesWeb Mercator tilesTissot’s indicatrixProjection comparisonWorld map (canvas)Bivariate choroplethColor legendStyled axesGraticule labels (stereographic)Voronoi labelsPie chart componentBubble chart componentScatterplot with shapesRealtime horizon chartRidgeline plotParallel coordinatesThreshold encodingGradient encodingVariable-color lineMarey’s TrainsMarimekkoChord diagramHierarchical edge bundling IIHierarchical edge bundlingArc diagramMobile patent suitsForce-directed treeTree of LifeIndented treeCircle packing componentNested treemapCascaded treemapParallel setsNormal quantile plotQ–Q PlotHexbin mapHexbin (area)HexbinContoursDensity contoursKernel density estimationMoving averageSeamless zoomable map tilesZoomable bar chartZoomable area chartPannable chartBrushable scatterplot matrixBrushable scatterplotVersor draggingZoomable sunburstZoomable icicleCollapsible treeZoomable circle packingZoomable treemapHierarchical bar chartWorld tourOrthographic to equirectangularZoom to bounding boxSmooth zoomingStreamgraph transitionsStacked-to-grouped barsBar Chart RaceScatterplot tourTemporal force-directed graphAnimated treemap
Also listed in…
Visualization
Insert cell
Insert cell
Insert cell
viewof value = {
// Specify the chart’s dimensions.
const width = 928;
const height = 600;
const marginTop = 20;
const marginRight = 40;
const marginBottom = 30;
const marginLeft = 40;

// Create the horizontal time scale.
const x = d3.scaleUtc()
.domain(d3.extent(stocks, d => d.Date))
.range([marginLeft, width - marginRight])
.clamp(true)

// Normalize the series with respect to the value on the first date. Note that normalizing
// the whole series with respect to a different date amounts to a simple vertical translation,
// thanks to the logarithmic scale! See also https://observablehq.com/@d3/change-line-chart
const series = d3.groups(stocks, d => d.Symbol).map(([key, values]) => {
const v = values[0].Close;
return {key, values: values.map(({Date, Close}) => ({Date, value: Close / v}))};
});

// Create the vertical scale. For each series, compute the ratio *s* between its maximum and
// minimum values; the path is going to move between [1 / s, 1] when the reference date
// corresponds to its maximum and [1, s] when it corresponds to its minimum. To have enough
// room, the scale is based on the series that has the maximum ratio *k* (in this case, AMZN).
const k = d3.max(series, ({values}) => d3.max(values, d => d.value) / d3.min(values, d => d.value));
const y = d3.scaleLog()
.domain([1 / k, k])
.rangeRound([height - marginBottom, marginTop])

// Create a color scale to identify series.
const z = d3.scaleOrdinal(d3.schemeCategory10).domain(series.map(d => d.Symbol));

// For each given series, the update function needs to identify the date—closest to the current
// date—that actually contains a value. To do this efficiently, it uses a bisector:
const bisect = d3.bisector(d => d.Date).left;

// Create the SVG container.
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto; -webkit-tap-highlight-color: transparent;");

// Create the axes and central rule.
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
.call(g => g.select(".domain").remove());

svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y)
.ticks(null, x => +x.toFixed(6) + "×"))
.call(g => g.selectAll(".tick line").clone()
.attr("stroke-opacity", d => d === 1 ? null : 0.2)
.attr("x2", width - marginLeft - marginRight))
.call(g => g.select(".domain").remove());
const rule = svg.append("g")
.append("line")
.attr("y1", height)
.attr("y2", 0)
.attr("stroke", "black");

// Create a line and a label for each series.
const serie = svg.append("g")
.style("font", "bold 10px sans-serif")
.selectAll("g")
.data(series)
.join("g");

const line = d3.line()
.x(d => x(d.Date))
.y(d => y(d.value));

serie.append("path")
.attr("fill", "none")
.attr("stroke-width", 1.5)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke", d => z(d.key))
.attr("d", d => line(d.values));

serie.append("text")
.datum(d => ({key: d.key, value: d.values[d.values.length - 1].value}))
.attr("fill", d => z(d.key))
.attr("paint-order", "stroke")
.attr("stroke", "white")
.attr("stroke-width", 3)
.attr("x", x.range()[1] + 3)
.attr("y", d => y(d.value))
.attr("dy", "0.35em")
.text(d => d.key);

// Define the update function, that translates each of the series vertically depending on the
// ratio between its value at the current date and the value at date 0. Thanks to the log
// scale, this gives the same result as a normalization by the value at the current date.
function update(date) {
date = d3.utcDay.round(date);
rule.attr("transform", `translate(${x(date) + 0.5},0)`);
serie.attr("transform", ({values}) => {
const i = bisect(values, date, 0, values.length - 1);
return `translate(0,${y(1) - y(values[i].value / values[0].value)})`;
});
svg.property("value", date).dispatch("input"); // for viewof compatibility
}

// Create the introductory animation. It repeatedly calls the update function for dates ranging
// from the last to the first date of the x scale.
d3.transition()
.ease(d3.easeCubicOut)
.duration(1500)
.tween("date", () => {
const i = d3.interpolateDate(x.domain()[1], x.domain()[0]);
return t => update(i(t));
});

// When the user mouses over the chart, update it according to the date that is
// referenced by the horizontal position of the pointer.
svg.on("mousemove touchmove", function(event) {
update(x.invert(d3.pointer(event, this)[0]));
d3.event.preventDefault();
});

// Sets the date to the start of the x axis. This is redundant with the transition above;
// uncomment if you want to remove the transition.
// update(x.domain()[0]);
return svg.node();
}
Insert cell
Insert cell
stocks = (await Promise.all([
FileAttachment("AAPL.csv").csv({typed: true}).then((values) => ["AAPL", values]),
FileAttachment("AMZN.csv").csv({typed: true}).then((values) => ["AMZN", values]),
FileAttachment("GOOG.csv").csv({typed: true}).then((values) => ["GOOG", values]),
FileAttachment("IBM.csv").csv({typed: true}).then((values) => ["IBM", values]),
FileAttachment("MSFT.csv").csv({typed: true}).then((values) => ["MSFT", values]),
])).flatMap(([Symbol, values]) => values.map(d => ({Symbol, ...d})))
Insert cell
Insert cell
Plot.plot({
y: {
type: "log",
grid: true,
label: "Change in price (%)",
tickFormat: ((f) => (x) => f((x - 1) * 100))(d3.format("+d"))
},
marks: [
Plot.ruleY([1]),
Plot.lineY(stocks, Plot.normalizeY({x: "Date", y: "Close", stroke: "Symbol"}))
]
})
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more