Chart.js:将标题/图例位置更改为右侧

问题描述 投票:0回答:1

我有一个顶部标题的条形图。如何将图例的位置更改为图表右侧。我在其他表格上搜索但找不到任何东西。这是我的代码:

let ctx = document.getElementById('canvas');
let chart = new Chart(ctx, {
        type: 'bar',
        data: {
                labels: [1, 2, 3, 4, 5],
                datasets: [{
                        label: 'Votes',
                        data: [1, 2, 3, 4, 5],
                        backgroundColor: 'rgba(255, 0, 0, 0.2)'
                }, {
                        label: 'Score',
                        data: [1, 2, 3, 4, 5],
                        backgroundColor: 'rgba(0, 255, 0, 0.2)'
                }]
        },
        options: {
                scales: {
                        yAxes: [{
                                ticks: {
                                        beginAtZero: true
                                }
                        }]
                }
        }
});
charts chart.js
1个回答
2
投票

您可以在图表选项中将图例的position属性设置为right,将图例放置在图表的右侧...

options: {
   legend: {
      position: 'right'
   },
   ...
}

ᴅᴇᴍᴏ

let ctx = document.getElementById('canvas').getContext('2d');
let chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: [1, 2, 3, 4, 5],
      datasets: [{
         label: 'Votes',
         data: [1, 2, 3, 4, 5],
         backgroundColor: 'rgba(255, 0, 0, 0.2)'
      }, {
         label: 'Score',
         data: [1, 2, 3, 4, 5],
         backgroundColor: 'rgba(0, 255, 0, 0.2)'
      }]
   },
   options: {
      legend: {
         position: 'right'
      },
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
© www.soinside.com 2019 - 2024. All rights reserved.