在图例中为Chart.js中的单个数据值显示多个标签

时间:2018-10-30 14:50:05

标签: javascript chart.js

我有使用Chart.js库构建的图形:

chart

通常,Sshare用红色和绿色两种颜色表示。但是,在图例中,Sshare仅显示第一个颜色值红色。

如何使两种共享颜色都显示在图例中?

我尝试在Chart.js文档中搜索解决方案,但找不到编辑图例属性的方法。

我的代码:

<script>
// chart colors //BLUE & RED & VERT
var colors = ['#007bff','#dc3545',"#008000"];
var colors_suggested =[];
var labels_in =[];
var mshare_value =[];
var svalues =[];
var data_work_in =[
     { "ID":12, "Les":  "AB", "Name":   "   AB_12", "Mmin": 75, "Sshare":   29},
     { "ID":13, "Les":  "BB", "Name":   "   BB_13", "Mmin": 26.8, "Sshare": 36}

];

for (var i = 0; i < data_work_in.length;i++)
{
    labels_in.push(data_work_in[i].Name+";"+data_work_in[i].Mill);
    mshare_value.push(data_work_in[i].Mmin);
    svalues.push(data_work_in[i].Sshare);
    if ( data_work_in[i].Sshare >= data_work_in[i].Mmin)
    colors_suggested.push(colors[2]);
    else {
    colors_suggested.push(colors[1]);
    }
}
var chBar = document.getElementById("chBar");
var chartData = {
// Label of Entity
labels: labels_in,
// Value of percent category RTI|| VSM ...
datasets: [{
    label: 'Mmin',
    data: mshare_value,
    backgroundColor: colors[0]
},
{
    label: 'Sshare',
    data: svalues,
    xAxisID:'xAxis1',
    backgroundColor: colors_suggested
}]

};

if (chBar) {
// new graph
new Chart(chBar, {
type: 'bar',
data: chartData,
options: {
    scales: {
            xAxes:[
            {
                barPercentage: 0.9,
                categoryPercentage: 0.7,
                id:'xAxis1',
                type:"category",
                ticks:{
                    callback:function(label){
                        var sublabel_x = label.split(";")[0];
                        var label_p = label.split(";")[1];

                        return sublabel_x;
                    }
                }
            },
            {
                id:'xAxis2',
                type:"category",
                gridLines: {
                    drawOnChartArea: false, // only want the grid lines for one axis to show up
                },
                ticks:{
                    callback:function(label){
                        var sublabel_x = label.split(";")[0];
                        var label_p = label.split(";")[1];
                        return label_p;
                    }
                }
            }],
        yAxes: [{
            ticks: {
                beginAtZero: false
            },
            scaleLabel: {
            display: true,
            labelString: '%'
        }
        }]
    },
    legend: {
        display: true,
        legendText : ['Mmin','Sshare']
     }
}
});
}
</script>

0 个答案:

没有答案