Public
Edited
Feb 28, 2024
64 forks
8 stars
Global temperature trendsBeeswarm, Log ScaleContoursDensity contoursBubble chart componentCircle packing componentExploring Data with Vega-LiteStreaming data into VegaVega-Lite Line ChartBrushable scatterplotVega-Lite ScatterplotNight Skies — Lights and Light Pollution WebGL GlobePhysics based t-SNEGraphvizRidgeline plotZoomable sunburstHierarchical edge bundlingMethods of Comparison, ComparedChord diagramA Guide to Guides: Axes & Legends in VegaPSR B1919+21HexbinStacked-to-grouped barsTree of LifeHeat indexZoomable circle packingMarimekkoVizsla and Vega-LiteDirectly labelling linesParallel coordinatesCollapsible treeTangled tree visualizationMarey’s TrainsWorld History TimelineSmall multiple chart cartogramThe Real MVP in the NBAAnimated treemapDensity Contour Matrix with BrushingStars and constellationsHertzsprung–Russell diagramThe Coronavirus landscapeGitHub BurndownCandlestick ChartConcentration values vs. TimeA few days of CO2 levels in my homeIrregular bins histogramELD ViewerDistributions and summary statistics - a collection of Plot examplesMermaidBivariate Bubble MapD3 galleryCalendar
Stacked bar chart
Dot plotConnected scatterplotCandlestick chartHistogramForce-directed graphDisjoint force-directed graphIndex chartSankey diagramLine chart, percent changeStacked area chartBubble chartArea chartHorizontal bar chartRadial tidy treeCircle packingIcicleStreamgraphTidy treeCluster treeSunburstHorizon chartBox plotScatterplotDifference chartBand chartBar chart transitionsTreemapLine chart, multiple seriesScatterplot matrixBrushable scatterplot matrixPlayfair's Wheat and Wages
Also listed in…
Gallery
d3-shape
Insert cell
Insert cell
Insert cell
chart = {
// Specify the chart’s dimensions.
const width = 928;
const height = 500;
const marginTop = 10;
const marginRight = 10;
const marginBottom = 20;
const marginLeft = 40;

// Determine the series that need to be stacked.
const series = d3.stack()
.keys(d3.union(data.map(d => d.age))) // distinct series keys, in input order
.value(([, D], key) => D.get(key).population) // get value for each series key and stack
(d3.index(data, d => d.state, d => d.age)); // group by stack then series key

// Prepare the scales for positional and color encodings.
const x = d3.scaleBand()
.domain(d3.groupSort(data, D => -d3.sum(D, d => d.population), d => d.state))
.range([marginLeft, width - marginRight])
.padding(0.1);

const y = d3.scaleLinear()
.domain([0, d3.max(series, d => d3.max(d, d => d[1]))])
.rangeRound([height - marginBottom, marginTop]);

const color = d3.scaleOrdinal()
.domain(series.map(d => d.key))
.range(d3.schemeSpectral[series.length])
.unknown("#ccc");

// A function to format the value in the tooltip.
const formatValue = x => isNaN(x) ? "N/A" : x.toLocaleString("en")

// 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;");

// Append a group for each series, and a rect for each element in the series.
svg.append("g")
.selectAll()
.data(series)
.join("g")
.attr("fill", d => color(d.key))
.selectAll("rect")
.data(D => D.map(d => (d.key = D.key, d)))
.join("rect")
.attr("x", d => x(d.data[0]))
.attr("y", d => y(d[1]))
.attr("height", d => y(d[0]) - y(d[1]))
.attr("width", x.bandwidth())
.append("title")
.text(d => `${d.data[0]} ${d.key}\n${formatValue(d.data[1].get(d.key).population)}`);

// Append the horizontal axis.
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0))
.call(g => g.selectAll(".domain").remove());

// Append the vertical axis.
svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y).ticks(null, "s"))
.call(g => g.selectAll(".domain").remove());

// Return the chart with the color scale as a property (for the legend).
return Object.assign(svg.node(), {scales: {color}});
}
Insert cell
data = {
const data = await FileAttachment("us-population-state-age.csv").csv({typed: true});
return data.columns.slice(1).flatMap((age) => data.map((d) => ({state: d.name, age, population: d[age]})));
}
Insert cell
import {legend} from "@d3/color-legend"
Insert cell
Insert cell
Plot.plot({
width: 928,
y: {transform: (d) => d / 1e6},
color: {scheme: "spectral"},
marks: [Plot.barY(data, {x: "state", y: "population", fill: "age", sort: {color: null, x: "-y"}})]
})
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