Chart.js compress vertical axis on barchart

江枫思渺然 提交于 2021-02-04 22:15:49

问题


I have a dataset in which the last value is always very high. This causes an issue with my bar chart; almost all the other values are hard to get a feeling for without hovering over them.

Here is a screenshot:

This is what I am trying to achieve;

So my question; is this possible within vanilla Chart.js or do I need a plugin? And if so; is there an existing plugin or do I need to write one myself?

I am also open for alternative solutions to the initial problem.

I've looked all over the internet for something like this but unfortunately without much luck.


回答1:


You can use logarithmic type yAxis

Default: linear

https://www.chartjs.org/docs/latest/axes/cartesian/logarithmic.html

var ctx = document.getElementById('myChart');

var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [{
      label: "Series 1",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [65, 59, 43, 81, 56, 950],
    }]
  },
  options: {
    scales: {
      yAxes: [{
        type: 'logarithmic',
        ticks: {
          callback: function(tick, index, ticks) {
            return tick.toLocaleString();
          }
        }
      }]
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart" width="400" height="200"></canvas>

Optimized ticks

50 * (Math.floor(i / 50)), // lower 50
50 * (Math.ceil(i / 50)) // higer 50

var ctx = document.getElementById('myChart');

var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [{
      label: "Series 1",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [65, 59, 43, 81, 56, 950],
    }]
  },
  options: {
    scales: {
      yAxes: [{
        type: 'logarithmic',
        ticks: {
          callback: function(tick, index, ticks) {
            return tick.toLocaleString();
          }
        },
        afterBuildTicks: function(pckBarChart) {
          pckBarChart.ticks = pckBarChart.chart.data.datasets[0].data.flatMap(i => [
            50 * (Math.floor(i / 50)), // lower 50
            50 * (Math.ceil(i / 50)) // higer 50
          ])
        }
      }]
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart" width="400" height="200"></canvas>


来源:https://stackoverflow.com/questions/59823030/chart-js-compress-vertical-axis-on-barchart

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