Published
Edited
Jul 21, 2021
1 star
Insert cell
md`# D3js bar chart test`
Insert cell
d3 = require("d3");
Insert cell
z = require("zebras");
Insert cell
url = "https://raw.githubusercontent.com/BeirutAI/medical-cost-prediction/master/data/insurance.csv"
Insert cell
data = d3.csv(url).then((data) => {
return z.parseNums(["age", "bmi", "children", "charges"], data);
});
Insert cell
charges = z.getCol("charges", data);
Insert cell
{
const width = 600;
const height = 500;
const margin = {
top: 10,
right: 10,
bottom: 25,
left: 30
}
const svg = DOM.svg(width, height);
svg.setAttribute("style", "background: #FFFFFF; border: 1px solid #000000;");
const x_scale = d3.scaleLinear()
.domain([d3.min(charges), d3.max(charges)])
.range([0, width - margin.left - margin.right])
.nice();
const x_axis = d3.axisBottom()
.scale(x_scale);
d3.select(svg)
.append("g")
.attr("transform", `translate(${margin.left},${height - margin.bottom})`)
.call(x_axis);
const hist = d3.histogram()
.value(d => d)
.domain(x_scale.domain())
.thresholds(x_scale.ticks(10));
const bins = hist(charges);
const y_scale = d3.scaleLinear()
.domain([0, d3.max(bins, d => d.length)])
.range([height - margin.top - margin.bottom, 0]);
const y_axis = d3.axisLeft()
.scale(y_scale);
d3.select(svg)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`)
.call(y_axis);
d3.select(svg)
.append("g")
.selectAll("rect")
.data(bins)
.enter()
.append("rect")
.attr("transform", d => `translate(${margin.left + x_scale(d.x0)},${margin.top + y_scale(d.length)})`)
.attr("width", d => (x_scale(d.x1) - x_scale(d.x0)) )
.attr("height", d => (height - margin.top - margin.bottom - y_scale(d.length)) )
.style("fill", "#3366CC");
return svg;
}
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