Search code examples
chart.jsreact-chartjsreact-chartjs-2

How to align labels at same side chartjs React


Hello i am rendering these charts using chart js but i am unable to align these charts in the same order my config file and options file is given below can anyone please help me with this. i tried with below options and data

const options = {
    indexAxis: "y",
    maintainAspectRatio: false,
    aspectRatio: 0.8,
    barThickness: 20,
    responsive: true,
    layout: {
        padding: {
            left: 1
        }
    },
    plugins: {
        legend: {
            display: false
        }
    },
    scales: {
        x: {
            ticks: {
                color: "#495057"
            },
            grid: {
                color: "#ebedef"
            }
        },
        y: {
            ticks: {
                color: "#495057",
                crossAlign: "near"
            },
            grid: {
                color: "#ebedef"
            },
            gridLines: {
                offsetGridLines: true,
                display: true
            }
        }
    }
};


const data = {
    labels: ["red"],
    datasets: [{
            backgroundColor: "#42A5F5",
            data: [65],
            borderWidth: 2,
            borderRadius: 75,
            borderSkipped: false
        },
        {
            backgroundColor: "#FFA726",
            data: [28],
            borderWidth: 2,
            borderRadius: 50,
            borderSkipped: false
        }
    ]
};

how to align one below the other labels


Solution

  • As far as I know chart.js does not provide an option to set a minimum distance for the labels, a workaround to achieve this is to add spaces the the labels of the charts where the labels are shorter as the longest one so you will get something like this:

    var options = {
      type: 'bar',
      data: {
        labels: ["                Red"],
        datasets: [{
          label: '# of Votes',
          data: [12],
          backgroundColor: 'pink'
        }]
      },
      options: {
        indexAxis: 'y'
      }
    }
    
    var 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.5.0/chart.js"></script>
    </body>