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

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

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

  1. const e80_array = <?php echo json_encode($e80_result_array) ?>;
  2. const e110_array = <?php echo json_encode($e110_result_array) ?>;
  3. const e80_avg_array = <?php echo json_encode($e80_avg) ?>;
  4. const e110_avg_array = <?php echo json_encode($e110_avg) ?>;
  5. const e80_serials= <?php echo json_encode($e80_serial) ?>;
  6. const e110_serials = <?php echo json_encode($e110_serial) ?>;
  7. // console.log(e80_array);
  8. // console.log(e80_avg_array);
  9. // console.log(e80_serials);
  10. const e80data = {
  11. labels: e80_serials,
  12. datasets: [
  13. {
  14. label: 'E80',
  15. data: [
  16. {x: e80_array, y: e80_avg_array}
  17. ],
  18. backgroundColor: 'rgba(255, 0, 0, 0.2)',
  19. borderColor: 'rgb(255, 0, 0)',
  20. borderWidth: 1
  21. }
  22. ]};
  23. const e80config = {
  24. type: 'scatter',
  25. data: e80data,
  26. options: {
  27. hoverRadius: 15
  28. }
  29. };
  30. var e80Chart = new Chart(
  31. document.getElementById('e80Chart'),
  32. e80config
  33. );

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

  1. Array [ "172", "172" ]

  1. Array [ "197.0", "193.0" ]
qvsjd97n

qvsjd97n1#

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

  1. data:[
  2. {x: [....], y: [....]}
  3. ]

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

  1. datasets: [
  2. {
  3. label: 'E80',
  4. data: e80_array,
  5. backgroundColor: 'rgba(255, 0, 0, 0.2)',
  6. borderColor: 'rgb(255, 0, 0)',
  7. borderWidth: 1
  8. },
  9. {
  10. label: 'E80_avg',
  11. data: e80_avg_array,
  12. backgroundColor: 'rgba(0, 0, 255, 0.2)',
  13. borderColor: 'rgb(0, 0, 255)',
  14. }
  15. ]}

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

  1. datasets: [
  2. {
  3. label: 'E80',
  4. data: e80_array.map((x, i)=>({x, y: e80_avg_array[i]})),
  5. backgroundColor: 'rgba(255, 0, 0, 0.2)',
  6. borderColor: 'rgb(255, 0, 0)',
  7. borderWidth: 1
  8. }
  9. ]

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

展开查看全部

相关问题