如何在chart.js中删除数据集时删除y轴

ars1skjm  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(211)

我需要向图表中添加多个数据集,并根据ID从图表中删除数据集。我使用yAxisID为每个数据集添加不同的y轴。从图表中删除数据集时,不会删除y轴。如何删除相应的y轴?
代码如下:

  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
  2. <div style="width: 400px;height: 200px;">
  3. <canvas id="myChart"></canvas>
  4. </div>
  5. <button onclick="add_dataset()">add dataset </button>
  6. <button onclick="remove_dataset()">remove random dataset</button>
  7. <script>
  8. const ctx = document.getElementById('myChart');
  9. my_chart = new Chart(ctx, {
  10. type: 'line',
  11. data: {
  12. labels: [0,1,2,3,4,5,6,7,8,9,10],
  13. datasets: [{
  14. label: "0",
  15. yAxisID: "0",
  16. data: Array.from({length: 10}, () => Math.floor(Math.random() * 10)),
  17. backgroundColor: getRandomColor(),
  18. }]
  19. },
  20. options: {
  21. responsive: true,
  22. },
  23. });
  24. function getRandomColor() {
  25. var letters = '0123456789ABCDEF'.split('');
  26. var color = '#';
  27. for (var i = 0; i < 6; i++) {
  28. color += letters[Math.floor(Math.random() * 16)];
  29. }
  30. return color;
  31. }
  32. function add_dataset(){
  33. temp = Array.from({length: 10}, () => Math.floor(Math.random() * 10));
  34. let data_store = {
  35. label: String(my_chart.data.datasets.length),
  36. yAxisID: String(my_chart.data.datasets.length),
  37. data: temp,
  38. backgroundColor: getRandomColor(),
  39. };
  40. my_chart.data.datasets.push(data_store)
  41. my_chart.update();
  42. }
  43. function remove_dataset(){
  44. let temp_num = Math.floor(Math.random() * my_chart.data.datasets.length);
  45. my_chart.data.datasets.splice(temp_num, 1);
  46. my_chart.update();
  47. }
  48. </script>

我试着从我的图表中删除刻度,但没有效果。

8nuwlpux

8nuwlpux1#

options对象中,尝试:

  1. options: {
  2. responsive: true,
  3. scales: {
  4. [yAxisId]: {
  5. display: false,
  6. },
  7. },
  8. }

相关问题