如何在右中心对齐Chart JS“图例”

时间:2019-05-16 10:49:58

标签: javascript charts chart.js bar-chart

我正在使用Chart JS version 2.x。我已经用图表JS准备了条形图。但是我喜欢在legend中对齐图表的right center。我在下面分享图片。

enter image description here

还有我想要的图例位置。

enter image description here

我从documentation开始尝试过。在我的代码中

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

更新1:我正在使用chart js module in Angular5

更新2:我尝试过的是https://jsfiddle.net/v4ur38ao/1/

1 个答案:

答案 0 :(得分:1)

使用最新版本的chart.js:https://www.chartjs.org/dist/master/Chart.min.js以获取更多参考信息check this documentation,并在图例中添加align:'middle'将会有效

legend: {
    position: "right",
    align: "middle"
},

var model = {
    type: "bar",
    data: {
        labels: ["APP1", "APP2", "APP3", "APP4", "APP5"],
        datasets: [{
            data: [25, 61, 47, 45, 30],
            label: "Response > 5",
            borderColor: "#5151A1",
            backgroundColor: "#5151A1"
        }, {
            data: [22, 38, 53, 17, 55],
            label: "Response <= 5",
            borderColor: "#408040",
            backgroundColor: "#408040"
        }]
    },
    options: {
        responsive: true,
        legend: {
            position: "right",
            align: "middle"
        },
        scales: {

            yAxes: [{
                ticks: {
                    min: 0,
                    //max: 100,
                    callback: function(value) {
                        return value + "%"
                    }
                },
                scaleLabel: {
                    display: true
                    //labelString: "Percentage"
                }
            }]
        }
    }
}


new Chart(document.getElementById("canvas").getContext("2d"), model);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.chartjs.org/dist/master/Chart.min.js"></script>

<canvas id="canvas" height="450" width="600"></canvas>

Check your updted fiddle here

如果npm install chart.js不起作用,请refer this answer了解更多详细信息,check the chart.js documentation