dpa*_*ssi 17 legend-properties pie-chart chart.js
我需要帮助将饼图的编号放在图例中
如果我用鼠标悬停图表我可以看到相对于每个项目的数字
我想在传奇中显示它
到目前为止重要的代码:
var tempData = {
labels: Status,
datasets: [
{
label: "Status",
data: Qtd,
backgroundColor: randColor
},
]
};
var ctx = $("#pieStatus").get(0).getContext("2d");
var chartInstance = new Chart(ctx, {
type: 'pie',
data: tempData,
options: {
title: {
display: true,
fontsize: 14,
text: 'Total de Pedidos por Situação'
},
legend: {
display: true,
position: 'bottom',
},
responsive: false
}
});
Run Code Online (Sandbox Code Playgroud)
"Qtd","randColor"已经是值"var"
tek*_*tiv 32
您需要generateLabels在选项中编辑属性:
options: {
legend: {
labels: {
generateLabels: function(chart) {
// Here
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里有一个小的jsFiddle,你可以看到它是如何工作的(编辑的行 - 来自38 - 被评论),结果如下:
小智 5
也许这是一个 hacky 解决方案,但对我来说似乎更简单。
filterChartJS 图例选项有一个filter参数。这是为每个图例项调用的函数,并且无论您是否要在图例中显示该项,它都会返回 true/false。
filter有 2 个参数:
legendItem:要显示/省略的图例项。它的属性在这里描述data:传递给图表的数据对象。由于 JS 通过引用传递对象,并filter为每个图例项调用,因此您可以改变legendItem对象以显示您想要的文本。
legend : {
labels: {
filter: (legendItem, data) => {
// First, retrieve the data corresponding to that label
const label = legendItem.text
const labelIndex = _.findIndex(data.labels, (labelName) => labelName === label) // I'm using lodash here
const qtd = data.datasets[0].data[labelIndex]
// Second, mutate the legendItem to include the new text
legendItem.text = `${legendItem.text} : ${qtd}`
// Third, the filter method expects a bool, so return true to show the modified legendItem in the legend
return true
}
}
}
Run Code Online (Sandbox Code Playgroud)