2024年6月30日

Obsidian-DataviewJS 绘制折线图

作者 Tamanegi
const targetDate = new Date("2024-06-27");
const files = app.vault.getMarkdownFiles().filter(file =>  {
return file.name.split(' ')[0] >= "2024-06-27" && file.path.includes("D01-日记/2024"); }
)
let data=[];
for(let file of files){
    let content = await app.vault.read(app.vault.getAbstractFileByPath(file.path));
    const weightLine = content.match(/体重:(\d+\.\d+)/);
            console.log("检查体重获取",weightLine);
            if (weightLine) {
                const weight = parseFloat(weightLine[1]);
                data.push({ date: file.name.substring(0, 10), weight: weight });
            }
}

 data.sort((a, b) => new Date(a.date) - new Date(b.date));

    // 准备绘图数据
    const dates = data.map(d => d.date);
    const weights = data.map(d => d.weight);

    // 使用Plotly绘制折线图
    const trace = {
        x: dates,
        y: weights,
        type: 'scatter',
        mode: 'lines+markers+text',
        marker: { color: 'blue' },
        text: weights.map(weight => `${weight} kg`), // 映射weights数组到文本,添加单位 
        textposition: 'top center' // 设置文本的位置
    };
    console.log("trace",trace);

    const layout = {
        title: '体重变化折线图',
        xaxis: { title: '日期' },
        yaxis: { title: '体重 (kg)' }
    };
    window.renderPlotly(this.container,[trace], layout);