Notebooks 2.0 is here.

Public
Edited
Feb 29, 2024
Insert cell
Insert cell
Insert cell
dataset = d3.csvParse(await FileAttachment("data.csv").text(), rowConverter);
Insert cell
rowConverter = (row) => {
// Modify code here for row conversion
row.hours_of_sleep = parseFloat(row.hours_of_sleep);
return {...row};
}
Insert cell
w = 600
Insert cell
h = 500
Insert cell
makeChart()
Insert cell
function makeChart() {
// sort by date ascending
dataset.sort((a,b) => a.date - b.date);

console.log(dataset);

const numDaysSlider = html`
<input id="numDaysSlider" type="range" min="1" max="7" value="7"></input>
`;
const daysText = html`
<span id="daysText">7</span>
`;
const svg = d3.create('svg')
.attr('width', w)
.attr('height', h);
let xScale = d3.scaleTime()
.domain(d3.extent(dataset, (d) => new Date(d.date)))
.range([0, w-100]);

let yScale = d3.scaleLinear()
.domain([0,12])
.range([20, h-20]);

let cScale = d3.scaleLinear()
.domain([0, 12])
.range(['red', 'orange']);

let width = w / dataset.length - 40;

svg
.selectAll("rect")
.data(dataset)
//.join("rect")
.join(
enter => enter.append('rect')
.attr("x", (d,i) => 20 + i * width)
.attr("y", (d) => h - 20 - yScale(d.hours_of_sleep))
.attr("width", width)
.attr("height", (d) => yScale(d.hours_of_sleep))
.style("fill", (d) => cScale(d.hours_of_sleep)),
update => update.transition()
.duration(2000)
.attr("x", (d,i) => 20 + i * width)
.attr("width", width)
);

const xAxis = svg
.append("g")
.classed("axis", true)
.attr("transform", `translate(20, ${h - 20})`)
.call(d3.axisBottom(xScale).tickFormat(d3.timeFormat("%a")));
const yAxis = svg
.append("g")
.classed("axis", true)
.attr("transform", `translate(20, 0)`)
.call(d3.axisLeft(yScale));
function updateGraph() {
const numDays = +numDaysSlider.value;
daysText.innerText = numDays;
let width = w / numDays - 40;
}
numDaysSlider.addEventListener('input', updateGraph);
return html`
<h1>Sleep</h1>
<label>Days to Show</label>
${numDaysSlider}
${daysText}
<div>${svg.node()}</div>
<!-- add any necessary HTML here, either directly or using the pattern
set by numDaysSlider & daysText
-->
`;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@7")
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