Published
Edited
Sep 15, 2020
3 forks
1 star
Insert cell
Insert cell
svg = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

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

g.append("g")
.call(d3.axisBottom(x))
.attr("transform", `translate(0, ${height - margin.top - margin.bottom})`)
.call(axis =>
axis
.append("text")
.text(xAttr)
.style("fill", "black")
.attr("transform", `translate( ${iwidth}, -10)`)
.style("text-anchor", "end")
);
g.append("g")
.call(d3.axisLeft(y))
.call(axis =>
axis
.append("text")
.text(yAttr)
.style("fill", "black")
.style("text-anchor", "middle")
.attr("y", -15)
);

// Your marks here
g.selectAll(".bar")
.data(groupedData)
.join("rect")
.attr("class", "bar")
.attr("x", gr => x(gr[0]))
.attr("width", x.bandwidth())
.attr("height", gr => iheight - y(gr[1].length))
.attr("y", gr => y(gr[1].length))
.style("fill", "steelblue");

// Your marks here
g.selectAll(".value")
.data(groupedData)
.join("text")
.attr("class", "value")
.attr("x", gr => x(gr[0]) + x.bandwidth() / 2)
.attr("y", gr => y(gr[1].length) - 3)
.style("fill", "black")
.style("font-size", "8pt")
.text(gr => gr[1].length);

return svg.node();
}
Insert cell
groupedData = d3.groups(data, d => d[xAttr])
Insert cell
iwidth = width - margin.left - margin.right
Insert cell
iheight = height - margin.top - margin.bottom
Insert cell
xAttr = "Species"
Insert cell
yAttr = "Count"
Insert cell
x = d3
.scaleBand()
.domain(data.map(d => d[xAttr]))
.padding(0.3)
.range([0, iwidth])
Insert cell
y = d3
.scaleLinear()
.domain([0, d3.max(groupedData, gr => gr[1].length)])
.range([iheight, 0])
.nice()
Insert cell
height = 400
Insert cell
margin = ({ left: 50, top: 30, right: 20, bottom: 20 })
Insert cell
md`## Data`
Insert cell
data = vegaDatasets["penguins.json"]()
Insert cell
vegaDatasets = require("vega-datasets@2")
Insert cell
d3 = require("d3@6")
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