Chart.js散点图数据不使用php中的数组常量

pobjuy32  于 2023-04-30  发布在  Chart.js
关注(0)|答案(1)|浏览(183)

我正在尝试使用图表。js以数组作为x和y值制作散点图。我在文件前面使用php从sql查询中获取这些数组的内容。它似乎工作时,我输入整数,但不与我的const数组。我使用了一个非常类似的方法来显示线图,但我有问题的散点图。我对JavaScript也很陌生,所以这并没有让事情变得更容易。任何反馈将不胜感激。

const e80_array = <?php echo json_encode($e80_result_array) ?>;
    const e110_array = <?php echo json_encode($e110_result_array) ?>;

    const e80_avg_array = <?php echo json_encode($e80_avg) ?>;
    const e110_avg_array = <?php echo json_encode($e110_avg) ?>;

    const e80_serials= <?php echo json_encode($e80_serial) ?>;
    const e110_serials = <?php echo json_encode($e110_serial) ?>;

    // console.log(e80_array);
    // console.log(e80_avg_array);
    // console.log(e80_serials);

    const e80data = {
    labels: e80_serials,
    datasets: [
        {
            label: 'E80',
            data: [
                {x: e80_array, y: e80_avg_array}
            ],
            backgroundColor: 'rgba(255, 0, 0, 0.2)',
            borderColor: 'rgb(255, 0, 0)',
            borderWidth: 1
        }
    ]};

    const e80config = {
    type: 'scatter',
    data: e80data,
    options: {
        hoverRadius: 15
    }
  };
 
  var e80Chart = new Chart(
    document.getElementById('e80Chart'),
    e80config
  );

我已经确保我的sql查询收集了正确的数据,并将它们正确地形成数组。当我安慰log(e80_array)和console。log(e80_avg_array)我在Web浏览器控制台中获取。..

Array [ "172", "172" ]

Array [ "197.0", "193.0" ]
qvsjd97n

qvsjd97n1#

问题在于您提供data的方式。格式

data:[
    {x: [....], y: [....]}
]

无法被图表识别。js。
如果你想显示e80 * 和 * e80_avg相对于e80_serials,你应该定义两个数据集:

datasets: [
        {
            label: 'E80',
            data: e80_array,
            backgroundColor: 'rgba(255, 0, 0, 0.2)',
            borderColor: 'rgb(255, 0, 0)',
            borderWidth: 1
        },
        {
            label: 'E80_avg',
            data: e80_avg_array,
            backgroundColor: 'rgba(0, 0, 255, 0.2)',
            borderColor: 'rgb(0, 0, 255)',
        }
    ]}

jsFiddle。在这种情况下,line图表类型会更容易。
如果你想绘制e80_avg相对于e80的图,你必须把每对数据作为一个项:[{x: 172, y: 190}, {x: 172, y:183}, ....]

datasets: [
        {
            label: 'E80',
            data: e80_array.map((x, i)=>({x, y: e80_avg_array[i]})),
            backgroundColor: 'rgba(255, 0, 0, 0.2)',
            borderColor: 'rgb(255, 0, 0)',
            borderWidth: 1
        }
    ]

jsFiddle。在这种情况下,您不需要标签。

相关问题