使用chartjs绘制函数图的问题

vulvrdjw  于 2023-04-20  发布在  Chart.js
关注(0)|答案(1)|浏览(188)

我试图用chartjs绘制一个函数,但遇到了一些麻烦
我不知道为什么xAxis标签有这些数字。
有没有更好的方法我应该采取?因为我认为这段代码是不好的
我怎样才能使图形的最高值出现在y轴标签上?

  1. const ctx = document.getElementById('myChart');
  2. const xAxis = []
  3. for(let i = 0; i < 1 ; i=i+0.001){
  4. xAxis.push(i)
  5. }
  6. const yAxis = []
  7. for(let i = 0 ; i < xAxis.length;i++){
  8. yAxis.push(1225*Math.pow(xAxis[i],48)*Math.pow((1-xAxis[i]),2))
  9. }
  10. new Chart(ctx, {
  11. type: 'line',
  12. data: {
  13. labels: xAxis,
  14. datasets: [{
  15. label: 'F(x)',
  16. data: yAxis,
  17. borderWidth: 1,
  18. fill: false,
  19. pointRadius: 0
  20. }]
  21. },
  22. options: {
  23. scales: {
  24. y: {
  25. beginAtZero: true,
  26. },
  27. x:{
  28. ticks:{
  29. beginAtZero : true,
  30. //maxTicksLimit : 1
  31. }
  32. }
  33. }
  34. }
  35. });
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <link rel="stylesheet" href="SRstyle.css">
  8. <title>Success Rate</title>
  9. </head>
  10. <body>
  11. <div class="chart-container">
  12. <canvas id="myChart"></canvas>
  13. </div>
  14. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  15. <script src="SRscript.js"></script>
  16. </body>
  17. </html>
92vpleto

92vpleto1#

默认情况下,对于折线图,X轴是一个“类别”轴,因此期望标签为字符串。数字的字符串表示是您正在设置的值。
按如下所示更改X轴配置,这将使其固定:

  1. scales: {
  2. y: {
  3. beginAtZero: true,
  4. },
  5. x:{
  6. type: 'linear', // <-- add this one
  7. beginAtZero : true, // <-- axis option, not ticks one
  8. ticks:{
  9. //maxTicksLimit : 1
  10. }
  11. }
  12. }

还要注意的是,beginAtZero选项是一个轴选项,而不是一个刻度,因此您应该将其移动到更高的级别。

展开查看全部

相关问题