Maxime Crtgn
Maxime Crtgn

Reputation: 265

Chartjs and datalabels : automatic y axis (and dynamic data) hide datalabels

I have a chart (chartjs) with labels (datalabels). When my data changes, my chart updates automatically. However, the largest datalabels are most of the time hidden by the automatic resizing of the y axis. Do you have any idea to fix that ?

enter image description here

It should be a 3 up there :)

Here is my code:

const completionOptions = {
        responsive: true,
        plugins: {
            legend: {
                display: false,
            },
            tooltip: {
                backgroundColor: 'rgb(85, 85, 85, 1)',
                displayColors: false,
                // https://www.chartjs.org/docs/latest/configuration/tooltip.html
            },
            datalabels: {
                color: 'rgb(203, 203, 203)',
                anchor: 'end',
                align: 'end',
                labels: {
                    title: {
                        font: {
                            family: 'karla',
                            weight: '600',
                            size: 12,
                        },
                    }
                }
            }
        },
        scales: {
            display: false,
            y: {
                beginAtZero: true,
                display: false,
                grid: {
                    display: false,
                },
                ticks: {
                    padding: 10
                }
            },
            x: {
                grid: {
                    display: false,
                },
                ticks: {
                    autoSkip: false,
                    maxRotation: 0,
                    minRotation: 0,
                    font: {
                        size: 20,
                    }
                }
            },
          }
    }

Upvotes: 1

Views: 444

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31439

You can use the grace option to add extra space to the y axes:

Chart.register(ChartDataLabels)

const options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 20, 3, 5, 2, 3],
      backgroundColor: 'pink'
    }]
  },
  options: {
    scales: {
      y: {
        grace: '10%'
      }
    },
    plugins: {
      legend: {
        display: false
      },
      datalabels: {
        anchor: 'end',
        align: 'end'
      }
    }
  }
}

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.8.0/chart.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</body>

Upvotes: 2

Related Questions