Public
Edited
Apr 25
1 star
Insert cell
Insert cell
//读取附件中数据,并转换为长数据格式
weight = {
const data = await FileAttachment("weight.csv").csv({ typed: true });
console.log(data.columns);
return data.flatMap((d) =>
data.columns
.slice(1)
.map((weight) => ({ date: d.date, weight, value: d[weight] }))
);
}
Insert cell
function wideToLong(
wideData,
idVars,
valueVars,
varName = "variable",
valueName = "value"
) {
return wideData.flatMap((item) => {
const idPart = {};
// 保留标识列
idVars.forEach((idVar) => {
idPart[idVar] = item[idVar];
});

// 转换每个值列
return valueVars.map((varNameCol) => {
return {
...idPart,
[varName]: varNameCol,
[valueName]: item[varNameCol]
};
});
});
}
Insert cell
//手动敲每天的数据
weightData = {
const data = [
{
date: new Date("2025-04-25"),
weight: 73.2
},
{
date: new Date("2025-04-24"),
weight: 73.7
},
{
date: new Date("2025-04-12"),
weight: 72.5
},
{
date: new Date("2025-04-11"),
weight: 72.7
},
{
date: new Date("2025-04-10"),
weight: 70.7
}
];
return wideToLong(
data,
["date"], // 要保留的标识列
["weight"], // 要转换的值列
"time", // 新变量列名
"value" // 新值列名
);
}
Insert cell
//基于附件中数据进行画图
Plot.plot({
x: { line: true, insetRight: 40 },
y: { domain: [60, 80], axis: null },
marks: [
Plot.line(weightData, { x: "date", y: "value", stroke: "time" }),
Plot.text(weightData, {
x: "date",
y: "value",
text: "value",
fill: "currentColor",
stroke: "white",
strokeWidth: 8
}),
Plot.text(
weightData,
Plot.selectLast({
x: "date",
y: "value",
text: "time",
z: "time",
textAnchor: "start",
dx: 12,
fontWeight: "bold"
})
)
]
})
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