Search code examples
javascriptchartschart.jsdata-visualizationjavascript-objects

How can I put my label on the right hand side of my chart in Chartjs


I'm trying to put the title of my chart on the right hand side in Chartjs but I'm failing miserably. could someone please assist.

<script>
            const ctx = document.getElementById('myChart');
            const myChart = new Chart(ctx, {
                type : 'line',
                data : {
                    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                    datasets: [{
                        label: '# of Votes', 
                        data: [12, 19, 3, 5, 2, 3],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: ['1'],
                    }]
                },
                options : {
                  legend: {position: 'right'},
                  label: {display: true, text: '# of votes'},
                    scales: {
                        y: {
                            beginAtZero: true,
                        }
                    }
                }
            });
            </script>

I'm relatively new to JavaScript. so there is a lot I need to learn.


Solution

  • Assuming, you want to place the legend right of your chart, you need to define the option plugins.legend.position: 'right'.

    Further information is available at Chart.js documentation here.

    Please take a look at below runnable snippet and see how it works.

    new Chart('myChart', {
      type: 'bar',
      data: {
        labels: ['A', 'B', 'C', 'D'],
        datasets: [{
          label: 'Dataset',
          data: [4, 2, 5, 3],
        }]
      },
      options: {   
        plugins: {
          legend: {
            display: true,
            position: 'right'
          }
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
    <canvas id="myChart"></canvas>