Public
Edited
Apr 18, 2023
Insert cell
Insert cell
Superstore.csv
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
superstore_viz = {
// define plotting parameters
const barMargin = { top: 15, right: 15, bottom: 40, left: 80 };
const barWidth = 800;
const barHeight = 600;

const barX = d3
.scaleBand()
.domain(superstore.map((d) => d.Region))
// .domain(['Cotton','Wool','Cellulosics','Hemp','Polyamide','Polyester'])
.range([barMargin.left, barWidth])
.padding(0.1);

const barXAxis = (g) =>
g
.attr("transform", `translate(0, ${barHeight})`)
.call(d3.axisBottom().scale(barX));

const barY = d3
.scaleLinear()
.domain([0, d3.max(superstore, (d) => d.Quantity) + 15])
.range([barHeight, barMargin.top]);

const barYAxis = (g) =>
g
.attr("transform", `translate(${barMargin.left}, 0)`)
.call(d3.axisLeft().scale(barY));

// create the container
const svg = d3
.create("svg")
.attr("width", barWidth + barMargin.left + barMargin.right)
.attr("height", barHeight + barMargin.top + barMargin.bottom);

// add x axis
svg.append("g").call(barXAxis);
svg
.append("text")
.attr("x", barWidth / 2) // center label
.attr("y", barHeight + barMargin.bottom + barMargin.top - 5)
.attr("text-anchor", "middle")
// .attr("font-size", 10)
.attr("font-family", "sans serif")
.text("Region");

// add y axis
svg.append("g").call(barYAxis);
svg
.append("text")
// .attr("x", barWidth / 2) // center label
// .attr("y", barHeight)
// .attr("font-size", 10)
.attr("font-family", "sans serif")
.attr(
"transform",
`translate(${barMargin.left / 2}, ${barHeight / 2})rotate(-90)`
)
.attr("text-anchor", "middle")
.text("Purchase Quantity");

// hover effect for bats

// add bars
svg
.append("g")
.attr("id", "bars")
.selectAll("rect")
.data(superstore)
.join("rect")
.attr("width", barX.bandwidth())
.attr("x", (d) => barX(d.Region))
.attr("height", 0)
.attr("y", barHeight)
.attr("height", (d) => barHeight - barY(d.Quantity))
.attr("y", (d) => barY(d.Quantity))
.attr("stroke", "black")
.attr("fill", "lightgreen");
return svg.node();
}
Insert cell
tooltip_bars = {
let color = "darkgreen";
let rects = d3.select(superstore_viz).selection("g#bars").selectAll("rect");
rects.on("mouseover.highlight", function (d) {
let rect = d3.select(this);
rect
.attr("fill", color)
.append("svg:title")
.text((d) => {
return "State: " + d.State;
});
});
rects.on("mouseout.highlight", function (d) {
let rect = d3.select(this);
rect.attr("fill", "lightgreen");
});
}
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