【问题标题】:How can I put my label on the right hand side of my chart in Chartjs如何在 Chartjs 中将标签放在图表的右侧
【发布时间】:2022-01-23 15:32:27
【问题描述】:

我试图将图表的标题放在 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 比较陌生。所以我需要学习很多东西。

【问题讨论】:

    标签: javascript charts chart.js data-visualization javascript-objects


    【解决方案1】:

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

    更多信息请参见 Chart.js 文档here

    请看下面的可运行的 sn-p 看看它是如何工作的。

    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>

    【讨论】:

    • 谢谢它的工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多