chart.js 组合散点图和直线

chart.js combine scatter and line

我是 chart.js 的新手,我正在尝试将散点图与折线图结合起来。

我一直在努力解决 2 个问题:

1.- 我已经设法绘制了散点图,但是没有显示折线图。没有抛出错误消息。

2.- 我想在底部添加一些标签,但经过许多方法后,图表只显示 x 轴上的数字。

我附上了一张图片,这样你就可以看到我现在在哪里。我手动画了折线图。

这是我正在使用的代码:

<script>
const ctx = document.getElementById('myChart');

Chart.defaults.elements.point.pointStyle = 'dash';
Chart.defaults.elements.point.borderWidth = 2;
Chart.defaults.elements.point.radius = 12;

const labels1 = ['A', 'B','C','T','GW','RT','MJ','JY','YJ','TR','UY','IY','TR','RE','WE','WE','WE','BV','CS', 'EW'];

const data1 = {
    datasets: [
        {
        type: 'line',
        label: 'Line Dataset',
        data: [10, 10, 10, 10],
        backgroundColor: 'rgb(0, 0, 255)',
        borderColor: 'rgb(0, 0, 255)'
        },
        {
        type: 'scatter',
        backgroundColor: 'rgb(0, 0, 0)',
        borderColor: 'rgb(255, 0, 0)',
        data: [{x:1, y:36}, {x:1, y:37}, {x:1, y:40}, {x:1, y:40}, //.... and many more!!
        }

    ],

};


const myChart = new Chart(ctx, {
    type: 'scatter',
    data: data1,
    labels: labels1,
    options: {
        scales: {
            x: {
                min: 0,
                max: 19,
                ticks: {stepSize: 1}
            },
            y: {
                min: 20,
                max: 120,
                ticks: {stepSize: 10},
                grid:{display:false}
            },
        }
    }
});

</script>

我试过在很多地方放置 labels: labels1 但它们从未显示过。 如附图所示,折线图也未显示。

Chart.js 版本为 3.6.2

非常感谢任何帮助。

此致问候!

这是因为散点图默认使用线性轴作为 x 轴,折线图使用类别轴,它们彼此不兼容,因此您需要使用第二个 X 轴。您的标签数组也位于错误的位置,它应该位于配置的 data 部分:

const labels1 = ['A', 'B', 'C', 'T', 'GW', 'RT', 'MJ', 'JY', 'YJ', 'TR', 'UY', 'IY', 'TR', 'RE', 'WE', 'WE', 'WE', 'BV', 'CS', 'EW'];

const data1 = {
  labels: labels1, // place labels array in correct spot
  datasets: [{
      type: 'line',
      label: 'Line Dataset',
      data: [10, 10, 10, 10],
      backgroundColor: 'rgb(0, 0, 255)',
      borderColor: 'rgb(0, 0, 255)',
      xAxisID: 'x2' // Specify to which axes to link
    },
    {
      type: 'scatter',
      backgroundColor: 'rgb(0, 0, 0)',
      borderColor: 'rgb(255, 0, 0)',
      data: [{
        x: 1,
        y: 36
      }, {
        x: 1,
        y: 37
      }, {
        x: 1,
        y: 40
      }, {
        x: 1,
        y: 40
      }]
    }
  ],
}


const myChart = new Chart('chartJSContainer', {
  type: 'scatter',
  data: data1,
  options: {
    scales: {
      x: {
        min: 0,
        max: 19,
        ticks: {
          stepSize: 1
        }
      },
      x2: { // add extra axes
        position: 'bottom',
        type: 'category'
      },
      y: {
        min: 0,
        max: 120,
        ticks: {
          stepSize: 10
        },
        grid: {
          display: false
        }
      },
    }
  }
});
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>