How can I control the placement of my Chart.JS pie chart's legend, as well as its appearance?

前端 未结 3 1073
眼角桃花
眼角桃花 2021-02-05 07:01

I am able to create a pie chart using Chart.JS with this code:

HTML

3条回答
  •  后悔当初
    2021-02-05 07:19

    As @B.ClayShannon mentioned, version 2 is quite a bit different than verison 1. Here is an example of how to customize the legend template using version 2.

    options: {
        legendCallback: function (chart) {
            var text = [];
            text.push('
      '); for (var i = 0; i < chart.data.datasets[0].data.length; i++) { text.push('
    •  '); if (chart.data.labels[i]) { text.push(chart.data.labels[i]); } text.push('
    • '); } text.push('
    '); return text.join(''); }, legend: {display: false}, }

    It's not shown directly in the accepted solution above, but to render your legend elsewhere you'll want to call:

    $("#myChartLegend").html(myChart.generateLegend()); 
    

    Finally, some HTML to pull it together (note clearfix is a Bootstrap class that :

提交回复
热议问题