你如何用 chart.js 绘制散点图

How do you plot scatter graph with chart.js

我正在尝试弄清楚如何使用 chart.js 绘制散点图 我尝试绘制的数据是随机生成的,其中 datesdatetime.now() 对象的列表,并且prices 是一个浮点数列表

dates = [datetime.now().strftime("%Y-%m-%d")  for i in range(10)]
var dates_ = {{dates|tojson}}
var prices_ = {{prices|tojson}}
function parse_data(dates , prices)
{
    console.log(dates.length , prices.length)
    var tmp = [];
    for (let i = 0; i < dates.length; i++)
    {
        var x;
        var y;
        tmp[i] = {x: dates.at(i), y: prices.at(i)};
    }
    return tmp;
}
var data_ = parse_data(dates_, prices_);

var chart = new Chart(ctx, {
    type: 'scatter',
    data: {
        datasets: [{
        lablel: "some_data",
        data: data_}]
});

将日期转换为浮点数可以完成这项工作,但它将日期显示为数字,而且看起来不太好看

您可以按如下方式定义您的 x 轴

x: {      
  type: 'time',
  time: {
    parser: 'YYYY-M-D',
    unit: 'day',
    displayFormats: {
      day: 'D MMM YYYY'
    },
    tooltipFormat: 'D MMM YYYY'
  }
}

Further information can be found at the Chart.js documentation here and in the Chart.js samples here.

Note that I use chartjs-adapter-moment together with moment to make this work. The formats for parsing and displaying time values as desired can be found here.

请查看您修改后的代码,看看它是如何工作的。

var test = [
  { x: "2022-1-8", y: 950 },
  { x: "2022-1-9", y: 1100 },
  { x: "2022-1-10", y: 990 },
  { x: "2022-1-12", y: 1250 },
  { x: "2022-1-13", y: 1050 }
];

var chart = new Chart('chart-line', {
  type: 'scatter',
  data: {
    datasets: [{
      data: test,
      label: 'buys',
      borderColor: "#3e95cd"
    }]
  },
  options: {
    responsive: false,
    scales: {
      x: {      
        type: 'time',
        time: {
          parser: 'YYYY-M-D',
          unit: 'day',
          displayFormats: {
            day: 'D MMM YYYY'
          },
          tooltipFormat: 'D MMM YYYY'
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@1.0.0"></script>
<canvas id="chart-line" height="200"></canvas>

散点图在内部使用折线图,但对其进行了更改,因此 showLine 属性 变为假并且两个轴都设置为线性。

因此您只需在数据集中将 showLine 属性 设置为 false 并使用折线图。