最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Creating a Bar Graph to compare two values (graph doesn't always start at zero) - Stack Overflow

programmeradmin8浏览0评论

I have already entered the code to make the bar graph start at zero, although whenever my numInput.value becomes less than totalEmissions, the graph for some reason starts at numInput.value, rendering part of the chart unvisible.

Here is a code snippet of the js (When inputVal < totalEmissions):

    barGraphA = document.getElementById("BarGraphA")

    inputVal = 22 // this represents numInput.value
    totalEmissions = 26
    
    const maxValue = Math.max(totalEmissions, inputVal);
    const canvasHeight = maxValue * 10; // Adjust the multiplier as needed for better visibility

    barGraphA.innerHTML = `<canvas id="barChartA" style="width:100%; max-width:350px; height:${canvasHeight}px;"></canvas>`;

    new Chart("barChartA", {
        type: 'bar',
        data: {
            labels: ['Your Emissions', 'Your Estimate'],
            datasets: [{
                label: 'Tons of CO2 (Every Year)',
                data: [totalEmissions, inputVal],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                ],
                borderColor: [
                    'rgba(54, 162, 235, 1)',
                    'rgba(153, 102, 255, 1)',
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                    min: 0, // Start y-axis at 0
                    max: maxValue + 10 // Set max to a bit higher than the max value

                }
            }
        }
    });
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <div id="BarGraphA">
  </div>
  
  <script src="scripts.js"></script>
  <script
  src=".js/2.9.4/Chart.js">
  </script>
  
</body>
</html>

I have already entered the code to make the bar graph start at zero, although whenever my numInput.value becomes less than totalEmissions, the graph for some reason starts at numInput.value, rendering part of the chart unvisible.

Here is a code snippet of the js (When inputVal < totalEmissions):

    barGraphA = document.getElementById("BarGraphA")

    inputVal = 22 // this represents numInput.value
    totalEmissions = 26
    
    const maxValue = Math.max(totalEmissions, inputVal);
    const canvasHeight = maxValue * 10; // Adjust the multiplier as needed for better visibility

    barGraphA.innerHTML = `<canvas id="barChartA" style="width:100%; max-width:350px; height:${canvasHeight}px;"></canvas>`;

    new Chart("barChartA", {
        type: 'bar',
        data: {
            labels: ['Your Emissions', 'Your Estimate'],
            datasets: [{
                label: 'Tons of CO2 (Every Year)',
                data: [totalEmissions, inputVal],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                ],
                borderColor: [
                    'rgba(54, 162, 235, 1)',
                    'rgba(153, 102, 255, 1)',
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                    min: 0, // Start y-axis at 0
                    max: maxValue + 10 // Set max to a bit higher than the max value

                }
            }
        }
    });
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <div id="BarGraphA">
  </div>
  
  <script src="scripts.js"></script>
  <script
  src="https://cdnjs.cloudflare/ajax/libs/Chart.js/2.9.4/Chart.js">
  </script>
  
</body>
</html>

Here is a code snippet for when inputVal > totalEmissions:

 barGraphA = document.getElementById("BarGraphA")

    inputVal = 20 // this represents numInput.value
    totalEmissions = 18
    
    const maxValue = Math.max(totalEmissions, inputVal);
    const canvasHeight = maxValue * 10; // Adjust the multiplier as needed for better visibility

    barGraphA.innerHTML = `<canvas id="barChartA" style="width:100%; max-width:350px; height:${canvasHeight}px;"></canvas>`;

    new Chart("barChartA", {
        type: 'bar',
        data: {
            labels: ['Your Emissions', 'Your Estimate'],
            datasets: [{
                label: 'Tons of CO2 (Every Year)',
                data: [totalEmissions, inputVal],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                ],
                borderColor: [
                    'rgba(54, 162, 235, 1)',
                    'rgba(153, 102, 255, 1)',
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                    min: 0, // Start y-axis at 0
                    max: maxValue + 10 // Set max to a bit higher than the max value

                }
            }
        }
    });
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <div id="BarGraphA">
  </div>
  
  <script src="scripts.js"></script>
  <script
  src="https://cdnjs.cloudflare/ajax/libs/Chart.js/2.9.4/Chart.js">
  </script>
  
</body>
</html>

Share Improve this question edited Mar 19 at 23:49 Tuxedp asked Mar 19 at 12:08 TuxedpTuxedp 114 bronze badges 2
  • Please include a minimal reproducible example. Cannot reproduce the issue – 0stone0 Commented Mar 19 at 12:24
  • Cannot reproduce your issue in this demo – Yong Shun Commented Mar 19 at 14:05
Add a comment  | 

2 Answers 2

Reset to default 0

By symmetry, both example you provided do the same thing.

To make the Y axis start from zero, please use a more updated version of the chartjs library.

barGraphA = document.getElementById("BarGraphA")

    inputVal = 20 // this represents numInput.value
    totalEmissions = 18
    
    const maxValue = Math.max(totalEmissions, inputVal);
    const canvasHeight = maxValue * 10; // Adjust the multiplier as needed for better visibility

    barGraphA.innerHTML = `<canvas id="barChartA" style="width:100%; max-width:350px; height:${canvasHeight}px;"></canvas>`;

    new Chart("barChartA", {
        type: 'bar',
        data: {
            labels: ['Your Emissions', 'Your Estimate'],
            datasets: [{
                label: 'Tons of CO2 (Every Year)',
                data: [totalEmissions, inputVal],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                ],
                borderColor: [
                    'rgba(54, 162, 235, 1)',
                    'rgba(153, 102, 255, 1)',
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                    min: 0, // Start y-axis at 0
                    max: maxValue + 10 // Set max to a bit higher than the max value

                }
            }
        }
    });
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <div id="BarGraphA">
  </div>
  
  <script src="scripts.js"></script>
  <script src="https://cdn.jsdelivr/npm/chart.js"></script>
  
</body>
</html>

The current configuration that you used is for the Chart.JS version 3 and above, but you are working with Chart.JS version 2.

You can see the differences between the axis configuration between version 2 and 3: 3.x Migration Guide (Specific changes section)

Refer to Chart.JS 2 Ticks Configuration, the configuration for yAxes should be:

options: {
  scales: {
    yAxes: [
      {
        ticks: {
          beginAtZero: true,
          min: 0, // Start y-axis at 0
          max: maxValue + 10, // Set max to a bit higher than the max value
        },
      },
    ],
  },
}

Demo @ StackBlitz

Otherwise, would recommend that to use the latest Chart.JS (version 4.4.1).

发布评论

评论列表(0)

  1. 暂无评论