Values on Y-axis disappear (hide under labels)

喜你入骨 提交于 2020-01-15 09:17:32

问题


I use ChartJS library to create line chart. Somehow, the value on the Y values are almost hidden. I am wondering if I have set of data, how can I dynamically make y value so that it won't hide my y-value and still automatically scale base on my dataset selection.

And here is the CodePen

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [1510001367000, 1510001379000, 1510001415000, 1510001427000],
        datasets: [
          {
            label: 'dataset 1',
            fill: false,
            backgroundColor: 'rgb(255, 99, 132)',
            data: [72, 72, 72, 72]
          },
          {
            label: 'dataset 2',
            fill: false,
            backgroundColor: 'rgb(54, 162, 235)',
            data: [70, 70, 70, 70]
          }
        ]
    },
    options: {
      responsive: true      
    }
});
.myChartDiv {
  width: 600px;
  height: 800px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="800"></canvas>
    </div>
  </body>
</html>


回答1:


Thank you for the codepen, always helps to have these in a question!

You can set the min/max of the yAxis by adding the following scale options:

options: {
      responsive: true,
      scales:{
        yAxes:[{
          ticks:{
            suggestedMin:69,
            suggestedMax:73
          }
        }]
      }
    }

here is a forked CodePen

relevant docs here

You can always calculate the min and max as (min - 1) and (max +1) respectively to always get have an offset of 1.

UPDATE: =================================

In you're CodePen, you are using Chartjs 2.1.3, which is now an old version. Here is how you can build a simple plugin to add an offset to the linear char min/max:

first the plugin:

// Define a plugin to provide data labels
Chart.pluginService.register({
  beforeUpdate: function(chart) {
    // get custom defined offset
    var offset = chart.options.customOffset;
    // exisit gracefully if offset not defined or less than 0
    if(!offset || offset < 0) return;

    // preset the min and max
    var max = Number.MIN_VALUE;
    var min = Number.MAX_VALUE;

    // find min/max values of all datasets
    chart.data.datasets.forEach(function(dataset){
      var newMax = Math.max.apply(null, dataset.data);
      var newMin = Math.min.apply(null, dataset.data); 
      max = newMax > max ? newMax : max;
      min = newMin > min ? min : newMin;
    });
    // change min and max tick values
    chart.options.scales.yAxes[0].ticks.max = max + offset;
    chart.options.scales.yAxes[0].ticks.min = min - offset;
  }
});

now you can add a customOffset property to options:

 options: {
      customOffset: 0.1,
      responsive: true,
    }

Take a look at this CodePen

sample preview with 0.5 offset with your data:

UPDATE 2 =========================

Small changes to plugin so that when one dataset is hidden, the others are centered and the chart behave appropriately:

Chart.pluginService.register({
  beforeUpdate: function(chart){
    console.log("beforeUpdate");
    // get custom defined offset
    var offset = chart.options.customOffset;
    // exisit gracefully if offset not defined or less than 0
    if(!offset || offset < 0) return;

    // preset the min and max
    var max = Number.MIN_VALUE;
    var min = Number.MAX_VALUE;

    // find min/max values of all dataset
    chart.data.datasets.forEach(function(dataset){
      if(!dataset._meta[0].hidden){
        console.log(dataset)
        var newMax = Math.max.apply(null, dataset.data);
        var newMin = Math.min.apply(null, dataset.data); 
        max = newMax > max ? newMax : max;
        min = newMin > min ? min : newMin;
      }
    });
    // change min and max tick values
    chart.options.scales.yAxes[0].ticks.max = max + offset;
    chart.options.scales.yAxes[0].ticks.min = min - offset;
  }
});

CodePen

UPDATE 3 =========================

here is a plugin to add offset to ALL Y Axes in the chart:

Chart.pluginService.register({
    beforeUpdate: function(chart){
      console.log("beforeUpdate");
      // get custom defined offset
      var offset = chart.options.customOffset;
      // exisit gracefully if offset not defined or less than 0
      if(!offset || offset < 0) return;
      var yAxes = chart.options.scales.yAxes;
      for(var i=0; i<yAxes.length; i++){
        var axis = yAxes[i];
        var datasets = chart.data.datasets;
        var max = Number.MIN_VALUE;
        var min = Number.MAX_VALUE;
        var datasetsOnAxis = [];

        for(var j=0; j<datasets.length; j++){ // add datasets for this axes to datasetsOnAxis
          var dataset = datasets[j];
          var meta = chart.getDatasetMeta(j);
          if  (meta.yAxisID === axis.id) datasetsOnAxis.push(dataset); 
        }

        for(var k=0; k<datasetsOnAxis.length; k++){
          var dataset = datasetsOnAxis[k]
          var newMax = Math.max.apply(null, dataset.data);
          var newMin = Math.min.apply(null, dataset.data);
          max = newMax > max ? newMax : max;
          min = newMin > min ? min : newMin;
        }
        axis.ticks.max = max + offset;
        axis.ticks.min = min - offset;   
      }
    }
});


来源:https://stackoverflow.com/questions/47146427/values-on-y-axis-disappear-hide-under-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!