如何在 Chartjs 中将标签放在图表的右侧

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

我试图将图表的标题放在 Chartjs 的右侧,但我失败得很惨。有人可以帮忙吗。

<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>

我对 JavaScript 比较陌生。所以我需要学习的东西很多。

假设您想要将 legend 放在图表的右侧,您需要定义选项 plugins.legend.position: 'right'

Further information is available at Chart.js documentation here.

请查看下面的可运行代码段,看看它是如何工作的。

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>