Public
Edited
Apr 22
Importers
Insert cell
Insert cell
data = FileAttachment("Sleep_health_and_lifestyle_dataset.csv").csv({ typed: true })
Insert cell
viewof scatterPlot = scatterPlotWidget(data, { title: "Scatter Plot"});
Insert cell
function scatterPlotWidget(data, options = {}) {
// Create a container for the entire widget.
const container = html`<div style="font-family: sans-serif; display: flex; flex-direction: column; gap: 1rem;"></div>`;
// If a title is provided, add it.
if (options.title) {
const titleEl = html`<h3>${options.title}</h3>`;
container.append(titleEl);
}
// Extract the keys from the first object in the dataset.
const keys = Object.keys(data[0] || {});
// Helper: Checks if a column is numeric.
function isNumericColumn(key) {
return data.every(d => !isNaN(+d[key]));
}
// Only consider numeric columns for the scatter plot.
const numericKeys = keys.filter(isNumericColumn);
if (numericKeys.length < 2) {
container.append(html`<div style="color:red;">Dataset must have at least two numeric columns for scatter plot.</div>`);
return container;
}
// Create dropdown selectors for x-axis and y-axis.
const xSelect = Inputs.select(numericKeys, {label: "X Axis:", value: numericKeys[0]});
const ySelect = Inputs.select(numericKeys, {label: "Y Axis:", value: numericKeys[1]});
// Append the selectors to a controls div.
const controls = html`<div style="display: flex; gap: 1rem; align-items: center;"></div>`;
controls.append(xSelect, ySelect);
container.append(controls);
// Create a container for the plot.
const plotContainer = html`<div></div>`;
container.append(plotContainer);
// Update the scatter plot.
function updatePlot() {
// Clear out the old plot.
plotContainer.innerHTML = "";
const xKey = xSelect.value;
const yKey = ySelect.value;
// Generate a scatter plot
const plotNode = Plot.plot({
marks: [
Plot.dot(data, {x: xKey, y: yKey, r: 3, fill: "#4682b4"})
],
x: {label: xKey, tickCount: 10},
y: {label: yKey, tickCount: 10},
width: options.width || 500,
height: options.height || 400
});
plotContainer.append(plotNode);
}
// Update the plot whenever the selections change.
xSelect.addEventListener("input", updatePlot);
ySelect.addEventListener("input", updatePlot);
// Generate the initial plot.
updatePlot();
return container;
}
Insert cell
import {Inputs, html} from "@observablehq/inputs"
Insert cell
import {Plot} from "@observablehq/plot"
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