2

I'm using Chart.js v1.0.1-beta.3. I'm creating an interactive bar chart where users can click on a bar to increase the value of that bar.

By default, the histogram begins with empty values. The y-axis in that case defaults to a [0,1] scale. When users start adding data to the histogram, the y-axis maximum changes to adjust, which causes a jarring shift in the appearance of the graph at low values.

I'd like to have the y-axis default to, say, a [0,10] scale even when no data is entered. This StackOverflow question is the most relevant info I can find on how to address problems like this; the best solution on that page is to use the 'suggestedMax' parameter in the chart options:

scales: {
    yAxes: [{
        ticks: {
            suggestedMax : 10
        }
    }]
},

although this might apply only to v2+ of the library, it's hard to tell. In any event, this doesn't work, and the y-axis defaults to [1,0] when there's no data. I've also tried every combination of every other suggestion on that page, including using scaleOverride : true, display : true, setting explicit min and max parameters within 'ticks', scaleBeginsAtZero : true, beginAtZero : true, and scaleStartValue : 0,

If I try to upgrade to the most current release, v2.7.3, the charts don't appear on the rendered page at all. I don't have the time or inclination to debug what's happening there, so I'm stuck with v1.0.1.

How do I have a bar chart default to a suggested maximum in this version? Is it even possible?

PiotrChernin
  • 441
  • 8
  • 18

1 Answers1

1

Looking through the documentation included with v1.0.1 (zip file), there doesn't appear to be a way to do this. I can't see any option to set the scale values.

In v2.7.3 this is quite simple. A working example is below. The chart starts empty, with a y-axis scale from 0-10. Clicking 'Add Series' adds a new bar with a value of 5. Clicking a bar increments value by 1.

let btn1 = document.getElementById('add'),
  canvas = document.getElementById('chart'),
  chart = new Chart(canvas, {
    type: 'bar',
    data: {
      labels: [],
      datasets: []
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            min: 0,
            suggestedMax: 10
          }
        }]
      }
    }
  });

canvas.addEventListener('click', function(e) {
  let idx = chart.getDatasetAtEvent(e)[0]._datasetIndex;
  chart.config.data.datasets[idx].data[0]++;
  chart.update();
});

btn1.addEventListener('click', function() {
  chart.config.data.datasets.push({
    data: [5]
  });
  chart.update();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<button id="add">Add Series</button> Click a bar to increment its value by 1.
<canvas id="chart"></canvas>
timclutton
  • 12,682
  • 3
  • 33
  • 43