首页 > 解决方案 > Chart.js v3 - beginAtZero does nothing to my chart

问题描述

I read many threads on the beginAtZero parameter in Chart.js, but none of the solutions I found actually work for me.

I have a simple line chart with dates on my x axe and integers in my y axe. I can't manage to make my y axe start with 0.

 let atchoum = document.querySelector("#atchoum")
    let statchoum = new Chart(atchoum, {
        type: "line",
        data: {
            labels: {{ atchoumDate|raw }},
            datasets: [{
                label: "Nombre d'éternuements au support",
                data: {{ atchoumNb|raw }},
                borderColor: "blue",
                tension: 0.3,
                options: {
                    responsive: true,
                    scales: {
                       y: {
                           beginAtZero: true
                       }
                    },
                    animations: {
                        y: {
                            easing: 'easeInOutElastic',
                            from: (ctx) => {
                                if (ctx.type === 'data') {
                                    if (ctx.mode === 'default' && !ctx.dropped) {
                                        ctx.dropped = true;
                                        return 0;
                                    }
                                }
                            }
                        }
                    },
                }
            }]
        }
    })

标签: javascriptchart.js

解决方案


You are defining your options in the dataset itself. The options object is supposed to be on the same level as the type and data fields since the options are for the entire chart and not for a single dataset.

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 7, 9, 20, 8]
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>


推荐阅读