Public
Edited
Feb 1, 2023
Importers
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
histogram = (g) => {
// HISTOGRAM
// set the parameters for the histogram
const hist = d3
.histogram()
.value((d) => d[0]) // get value from the datum
.domain(x.domain()) // then the domain of the graphic
.thresholds(x.ticks(80)); // then the numbers of bins

// And apply this function to data to get the bins
let bins = hist(data);

const yHeight = y.range()[0] - y.range()[1];

// Y axis: scale and draw:
const yHist = d3
.scaleLinear()
.range([yHeight, 0])
.domain([0, d3.max(bins, (d) => d.length)]);

// append the bar rectangles to the svg element
return g
.selectAll(".histRect")
.data(bins)
.join("rect")
.attr("class", "histRect")
.attr("x", 1)
.attr("transform", function (d) {
return (
"translate(" + x(d.x0) + "," + (yHist(d.length) + margin.top) + ")"
);
})
.attr("width", function (d) {
return x(d.x1) - x(d.x0);
})
.attr("height", function (d) {
return yHeight - yHist(d.length);
})
.style("fill", color)
.style("stroke", "white");
}
Insert cell
title = (g) =>
g
.append("text")
.attr("text-anchor", "start")
.attr("font-family", "sans-serif")
.attr("font-size", "xlarge")
.attr("x", margin.left)
.attr("y", margin.top)
.attr("dx", ".5em")
.attr("dy", ".5em")
.text(titleText)
Insert cell
titleText = "Title"
Insert cell
xAxis = (g) =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(6))
.attr("font-size", "medium")
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left}, 0)`)
.call(d3.axisLeft(y).ticks(3))
Insert cell
x = d3.scaleTime(d3.extent(data, d => d[0]), [margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear(d3.extent(data, d => d[1]), [height - margin.bottom, margin.top])
Insert cell
height - margin.bottom - margin.top
Insert cell
margin = ({top: 10, right: 20, bottom: 20, left: 20})
Insert cell
height = 120
Insert cell
color = "#69b3a2"
Insert cell
Insert cell
Insert cell
Insert cell
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