Public
Edited
May 9
Insert cell
Insert cell
XLSX= require("xlsx")
Insert cell
mapData = {
const file = await FileAttachment("MapData@3.xlsx").arrayBuffer();
const workbook = XLSX.read(file, { type: "array" });
const sheet = workbook.Sheets[workbook.SheetNames[0]];
const data = XLSX.utils.sheet_to_json(sheet);
return data.map(d => ({
state: d["State"],
value: d3.format(".2f")(d["GSDP"])
}));
}
Insert cell
lineChartData = {
const file = await FileAttachment("LineChart@3.xlsx").arrayBuffer();
const workbook = XLSX.read(file, { type: "array" });
const sheet = workbook.Sheets[workbook.SheetNames[0]];
const data = XLSX.utils.sheet_to_json(sheet);

return data.map(d => ({
state: d["State"],
year: d["Year"],
value: d3.format(".2f")(d["GSDP"])
}));
}


Insert cell
// Load GeoJSON
geoData = FileAttachment("GeoData.json").json()

Insert cell
geoData.features.map(d => d.properties.ST_NM)
Insert cell
geoData.features.map(d => d.properties.ST_NM)
Insert cell
mapData.map(d => d.state)
Insert cell
mutable selectedState = null
Insert cell
mainView = {
if (!selectedState) return renderMap();
return renderLineChart(selectedState);
}

Insert cell
function renderMap() {
const width = 800;
const height = 800;

const svg = d3.create("svg")
.attr("width", width)
.attr("height", height); // Extra height for title

const path = d3.geoPath();

const projection = d3.geoIdentity()
.reflectY(true)
.fitSize([width, height], geoData);

path.projection(projection);

const values = mapData.map(d => d.value);
const meanValue = d3.mean(values);
const extent = d3.extent(values);
const maxAbs = d3.max([Math.abs(extent[0] - meanValue), Math.abs(extent[1] - meanValue)]);

const colorScale = d3.scaleDiverging()
.domain([meanValue - maxAbs, meanValue, meanValue + maxAbs])
.interpolator(d3.interpolateRdBu);

const colorMap = Object.fromEntries(mapData.map(d => [d.state, d.value]));

svg.selectAll("path")
.data(geoData.features)
.join("path")
.attr("d", path)
.attr("fill", d => colorScale(colorMap[d.properties.ST_NM] || 0))
.attr("stroke", "#000")
.attr("cursor", "pointer")
.on("click", (event, d) => {
mutable selectedState = d.properties.ST_NM;
});

// Add title
svg.append("text")
.attr("x", width-180)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-size", "38px")
.attr("font-weight", "bold")
.text("State's Per capita Income Map");

// Add subhead
svg.append("text")
.attr("x", width-230)
.attr("y", 70)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.selectAll("tspan")
.data([
"India’s per capita GSDP shows wide regional",
"disparities. Southern & western states lead,",
"while some populous northern states ",
"continue to lag economically."
])
.enter()
.append("tspan")
.attr("x",width-230)
.attr("dy", (d, i) => i === 0 ? 0 : 20) // Line spacing
.text(d => d);

// Legend dimensions (vertical)
const legendHeight = 200;
const legendWidth = 10;
const legendX = width - 60; // push to right
const legendY = height / 2 - legendHeight / 2;

// Create vertical gradient
const defs = svg.append("defs");

const gradient = defs.append("linearGradient")
.attr("id", "legend-gradient")
.attr("x1", "0%")
.attr("x2", "0%")
.attr("y1", "100%")
.attr("y2", "0%");

gradient.selectAll("stop")
.data([
{ offset: "0%", color: colorScale(0) },
{ offset: "50%", color: colorScale(meanValue) },
{ offset: "100%", color: colorScale(meanValue + maxAbs) }
])
.join("stop")
.attr("offset", d => d.offset)
.attr("stop-color", d => d.color);

// Draw the vertical bar
svg.append("rect")
.attr("x", legendX)
.attr("y", legendY)
.attr("width", legendWidth)
.attr("height", legendHeight)
.style("fill", "url(#legend-gradient)");

// Add vertical axis beside the legend
const legendScale = d3.scaleLinear()
.domain([0, meanValue + maxAbs])
.range([legendY + legendHeight, legendY]); // y-axis: bottom → top

const legendAxis = d3.axisRight(legendScale)
.tickValues([
0,
meanValue,
meanValue + maxAbs
])
.tickFormat(d3.format(".2f"));

svg.append("g")
.attr("transform", `translate(${legendX + legendWidth}, 0)`)
.call(legendAxis)
.selectAll("text")
.style("font-size", "16px");

const labeledStates = ["Maharashtra", "Karnataka", "Uttar Pradesh", "Tamil Nadu", "Madhya Pradesh", "Rajasthan", "Himachal Pradesh", "West Bengal"];

svg.selectAll("text.state-label")
.data(geoData.features.filter(d => labeledStates.includes(d.properties.ST_NM)))
.enter()
.append("text")
.attr("class", "state-label")
.attr("x", d => path.centroid(d)[0])
.attr("y", d => path.centroid(d)[1])
.attr("text-anchor", "middle")
.attr("alignment-baseline", "central")
.style("font-size", "16px")
.style("fill", "white")
.style("pointer-events", "none")
.text(d => d.properties.ST_NM);

return svg.node();
}

Insert cell
function renderLineChart(state) {
const stateData = lineChartData
.filter(d => d.state === state)
.map(d => ({ ...d, year: d.year.toString() }));

const container = html`<div style="position: relative;"></div>`;

// Back button
const backBtn = html`
<button style="
position: absolute;
top: 10px;
right: 10px;
z-index: 2;
background: #eee;
padding: 6px 12px;
border-radius: 5px;
border: none;
cursor: pointer;
">
← Back to Map
</button>
`;
backBtn.onclick = () => mutable selectedState = null;
container.append(backBtn);

if (stateData.length === 0) {
container.append(html`<div style="margin-top: 60px;">No data available for <b>${state}</b>.</div>`);
return container;
}

const margin = {top: 50, right: 30, bottom: 50, left: 80};
const width = 800 - margin.left - margin.right;
const height = 600 - margin.top - margin.bottom;

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

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

const x = d3.scaleBand()
.domain(stateData.map(d => d.year))
.range([0, width])
.padding(0.1);

const y = d3.scaleLinear()
.domain([0, d3.max(stateData, d => d.value)]).nice()
.range([height, 0]);

const line = d3.line()
.x(d => x(d.year) + x.bandwidth() / 2)
.y(d => y(d.value));

g.append("path")
.datum(stateData)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("d", line);

// Create tooltip div inside container
const tooltip = html`<div style="
position: absolute;
background: white;
border: 1px solid #ccc;
padding: 6px 10px;
border-radius: 4px;
pointer-events: none;
font-size: 18px;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
opacity: 0;
transition: opacity 0.3s;
z-index: 3;
"></div>`;
container.append(tooltip);

// Add dots
g.selectAll("circle")
.data(stateData)
.enter()
.append("circle")
.attr("cx", d => x(d.year) + x.bandwidth() / 2)
.attr("cy", d => y(d.value))
.attr("r", 4)
.attr("fill", "steelblue")
.on("mouseover", (event, d) => {
tooltip.style.opacity = 1;
tooltip.innerHTML = `<b>Year:</b> ${d.year}<br/><b>Value:</b> ₹${d3.format(".2f")(d.value)} lakh`;
})
.on("mousemove", (event) => {
const [xPos, yPos] = d3.pointer(event);
tooltip.style.left = `${xPos + margin.left + 20}px`;
tooltip.style.top = `${yPos + margin.top}px`;
})
.on("mouseout", () => {
tooltip.style.opacity = 0;
});

g.append("g")
.call(d3.axisLeft(y))
.selectAll("text")
.style("font-size", "18px");

g.append("g")
.attr("transform", `translate(0,${height})`)
.call(
d3.axisBottom(x)
.tickValues(stateData.map(d => d.year).filter((_, i) => i % 2 === 0)) // show every other year
)
.selectAll("text")
.attr("transform", "rotate(0)")
.style("text-anchor", "end")
.style("font-size", "18px");

svg.append("text")
.attr("x", (width + margin.left + margin.right) / 2)
.attr("y", 25)
.attr("text-anchor", "middle")
.style("font-size", "24px")
.text(`Per Capita GSDP - ${state}`);

container.append(svg.node());
return container;
}

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