Javascript 使用 ChartJS v2.0 自定义图例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37005297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:48:58  来源:igfitidea点击:

Custom Legend with ChartJS v2.0

javascriptchart.js

提问by Phil

I'm trying to create a custom legend template in ChartJS v2.0. In v1* of ChartJS I simply added a property to the new Chart constructor such as...

我正在尝试在 ChartJS v2.0 中创建自定义图例模板。在 ChartJS 的 v1* 中,我只是向新的 Chart 构造函数添加了一个属性,例如...

legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<li>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'

I can't seem to find any documentation in v2.0 for this option. Is it even available anymore? Can anyone show an example of how to accomplish this?

我似乎无法在 v2.0 中找到有关此选项的任何文档。它甚至可用了吗?任何人都可以展示如何实现这一目标的例子吗?

Thank you!

谢谢!

Update - Working code below

更新 - 下面的工作代码

legendCallback: function(chart) {
                console.log(chart.data);
                var text = [];
                text.push('<ul>');
                for (var i=0; i<chart.data.datasets[0].data.length; i++) {
                    text.push('<li>');
                    text.push('<span style="background-color:' + chart.data.datasets[0].backgroundColor[i] + '">' + chart.data.datasets[0].data[i] + '</span>');
                    if (chart.data.labels[i]) {
                        text.push(chart.data.labels[i]);
                    }
                    text.push('</li>');
                }
                text.push('</ul>');
                return text.join("");
            }

采纳答案by CraicerHyman

There is a legendCallbackfunction:

有一个legendCallback功能:

legendCallbackFunctionfunction (chart) { }
Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string.

legendCallback函数function (chart) { }
生成图例的函数。接收图表对象以从中生成图例。默认实现返回一个 HTML 字符串。

Details can be found here

详细信息可以在这里找到

see this issuefor the default legend callback:

请参阅此问题以了解默认图例回调:

legendCallback: function(chart) { 
    var text = []; 
    text.push('<ul class="' + chart.id + '-legend">'); 
    for (var i = 0; i < chart.data.datasets.length; i++) { 
        text.push('<li><span style="background-color:' + 
                   chart.data.datasets[i].backgroundColor + 
                   '"></span>'); 
        if (chart.data.datasets[i].label) { 
            text.push(chart.data.datasets[i].label); 
        } 
        text.push('</li>'); 
    } 
    text.push('</ul>'); 
    return text.join(''); 
}

回答by Robin Carlo Catacutan

If you guys run through this post and tried the posted answer and didn't work, try this one:

如果你们浏览了这篇文章并尝试了发布的答案但没有奏效,请尝试以下方法:

  legendCallback: function(chart) {
    var text = [];
    text.push('<ul>');
    for (var i=0; i<chart.data.datasets.length; i++) {
      console.log(chart.data.datasets[i]); // see what's inside the obj.
      text.push('<li>');
      text.push('<span style="background-color:' + chart.data.datasets[i].borderColor + '">' + chart.data.datasets[i].label + '</span>');
      text.push('</li>');
    }
    text.push('</ul>');
    return text.join("");
  },

Then add this below:

然后在下面添加:

document.getElementById('chart-legends').innerHTML = myChart.generateLegend();

To create the legends. Make sure you have an element <div id="chart-legends"></div>

创造传奇。确保你有一个元素<div id="chart-legends"></div>

回答by Udara Kasun

I hope this will helpful you

我希望这对你有帮助

var configd = {
    type: 'doughnut',
    data: {
        datasets: [{
            data: [
                50,
                60,
                20
            ],           
            backgroundColor: [
                '#33b35a',
                "#ffce56",
                "#4bc0c0",
                "#CDDC39",
                "#9C27B0",
                "#fb7145",
                "#5971f9"
            ],
            label: 'Energy usage'
        }],
        labels: [
            'E1',
            'E2',
            'E3'
        ]
    },
    options: {
        responsive: true,
        legend: {
            display: false
        },
        legendCallback: function (chart) {             
            // Return the HTML string here.
            console.log(chart.data.datasets);
            var text = [];
            text.push('<ul class="' + chart.id + '-legend">');
            for (var i = 0; i < chart.data.datasets[0].data.length; i++) {
                text.push('<li><span id="legend-' + i + '-item" style="background-color:' + chart.data.datasets[0].backgroundColor[i] + '"   onclick="updateDataset(event, ' + '\'' + i + '\'' + ')">');
                if (chart.data.labels[i]) {
                    text.push(chart.data.labels[i]);
                }
                text.push('</span></li>');
            }
            text.push('</ul>');
            return text.join("");
        },
        title: {
            display: false,
            text: 'Chart.js Doughnut Chart'
        },
        animation: {
            animateScale: true,
            animateRotate: true
        },
        tooltips: {
            mode: 'index',
            intersect: false,
            callbacks: {
                label: function (tooltipItem, data) {
                    let label = data.datasets[tooltipItem.datasetIndex].label + ' - ' + data.labels[tooltipItem.index];
                    let datasetLabel = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                    return label + ': ' + datasetLabel.toLocaleString();
                }
            }
        },
    }
};

 var ctxd = document.getElementById('canvas').getContext('2d');
    
    window.myDoughnut = new Chart(ctxd, configd);
    $("#do_legend").html(window.myDoughnut.generateLegend());

// Show/hide chart by click legend
updateDataset = function (e, datasetIndex) {    
    var index = datasetIndex;
    var ci = e.view.myDoughnut;
    var meta = ci.getDatasetMeta(0);    
    var result= (meta.data[datasetIndex].hidden == true) ? false : true;
    if(result==true)
    {
        meta.data[datasetIndex].hidden = true;
        $('#' + e.path[0].id).css("text-decoration", "line-through");
    }else{
        $('#' + e.path[0].id).css("text-decoration","");
        meta.data[datasetIndex].hidden = false;
    }
     
    ci.update();   
};
#do_legend{
   height:62px;
}

#do_legend{
    width:100%;     
}

#do_legend> ul{
    padding: 0;
    text-align: center;
}
 

#do_legend {   
  width:100%;
  bottom:10%;
}
#do_legend li {
    cursor: pointer;
    margin: 4px 3px;
    display: inline-table;
}
#do_legend li span {
    position: relative;
    padding: 3px 10px;
    border-radius: 13px;
    color: white;
    z-index: 2;
    font-size: 11px;
}

#do_legend{
    height: 62px;
    overflow-y: auto;
}

.donut-area{
    height:calc(100% - 62px)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>


<div style="width:40%">
   <div id="do_legend"></div>
  <canvas id="canvas"></canvas>
</div>

Codepen Example

代码笔示例

回答by Raji

This code is working for me

这段代码对我有用

updateDataset = function(target, chart, label, color, data) {
    var store = chart.data.datasets[0].label;
    var bgcolor = chart.data.datasets[0].backgroundColor;
    var dataSets = chart.data.datasets[0].data;
    var exists = false;
    for (var i = 0; i < chart.data.datasets[0].label.length; i++) {
        if (chart.data.datasets[0].label[i] === label) {
            chart.data.datasets[0].label
            exists = true;
            chart.data.datasets[0].label.push(store.splice(i, 1)[0][1]);
            chart.data.datasets[0].backgroundColor.push(bgcolor.splice(i, 1)[0][1]);
            chart.data.datasets[0].data.push(dataSets.splice(i, 1)[0][1]);      
        }
    }
    if (!exists) {
        chart.data.datasets[0].label.push(label);
        chart.data.datasets[0].backgroundColor.push(color);
        chart.data.datasets[0].data.push(data);
        exists = false;
    }
    chart.update();  
};