Chart.js 散点图的点格式数据

Chart.js point format data for a scatter plot

Chart.js 散点图只接受点格式 (x, y) 的数据。我正在尝试使用名为 meds.json 的文件中有关药物的信息来填充数据点 更具体地说,x 将是药物最后一次填充日期的月份,y 将是剂量。

如何从 meds.json 文件中获取所有这些数据并将其插入到数据中以创建散点图的点? 如果我尝试获取所有日期并将它们存储在一个数组中,并将所有剂量值存储在另一个数组中,我该如何使用这些数组来填充点数据?

这是使用 Chart.js 制作散点图的方法,我正在尝试填充数据 'data' 下的 x、y 点:

// charts.js
var scatterChart = new Chart(ctx, {
        type: 'scatter',
        data: {
            datasets: [{
                label: 'Scatter Dataset',
                data: [{
                    // x = month, y = dose
                    // fill these in for all meds in the json file
                    x: -10,
                    y: 0
                }, {
                    x: 0,
                    y: 10
                }, {
                    x: 10,
                    y: 5
                }]
            }]
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'linear',
                    position: 'top'
                }]
            }
        }
    });
}

meds.json

[
  {
    "name": "Simvastatin",
    "dose": 10,
    "dose unit": "mg",
    "freq": "qd",
    "route": "PO",
    "last fill date": "2/15/2020",
    "coverage": "100%",
    "anticipated remaining fills": 2
  },
  {
    "name": "Lisinopril",
    "dose": 5,
    "dose unit": "mg",
    "freq": "qd",
    "route": "PO",
    "last fill date": "2/15/2020",
    "coverage": "100%",
    "anticipated remaining fills": 2
  }  

    ...... The list goes on

]

您实际上应该为此使用折线图,这会更合适,并且可以准确显示趋势和月份与剂量之间的关系。

但是既然你要求散点图...你可以这样做:

const data = [{
    "name": "Simvastatin",
    "dose": 10,
    "dose unit": "mg",
    "freq": "qd",
    "route": "PO",
    "last fill date": "2/15/2020",
    "coverage": "100%",
    "anticipated remaining fills": 2
  },
  {
    "name": "Lisinopril",
    "dose": 5,
    "dose unit": "mg",
    "freq": "qd",
    "route": "PO",
    "last fill date": "2/15/2020",
    "coverage": "100%",
    "anticipated remaining fills": 2
  }
]

const transformedData = data.map(obj=>{
  return {
    x:new Date(obj["last fill date"]).getMonth() + 1,
    y:obj.dose,
  }
})

console.log(transformedData)

然后用作

var scatterChart = new Chart(ctx, {
        type: 'scatter',
        data: {
            datasets: [{
                label: 'Scatter Dataset',
                data: transformedData
            }]
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'linear',
                    position: 'top'
                }]
            }
        }
    });
}

希望对您有所帮助!