gpt4 book ai didi

javascript - ChartJS 在图例中显示值 (Chart.js V3.5)

转载 作者:行者123 更新时间:2023-12-05 00:52:43 27 4
gpt4 key购买 nike

我需要在数据名称之后显示图表的值,例如([数据颜色] Car 50,[color of data] Motorcycle 200)。我已经尝试更改图例标题的值,但它根本不起作用

这是我的代码

var ctx = document.getElementById('top-five').getContext('2d');
var myChartpie = new Chart(ctx, {
type: 'pie',
data: {
labels: {!! $top->pluck('name') !!},
datasets: [{
label: 'Statistics',
data: {!! $top->pluck('m_count') !!},
backgroundColor: {!! $top->pluck('colour') !!},
borderColor: {!! $top->pluck('colour') !!},
}]
},
options: {
plugins:{
legend:{
display:true,
title:{
text: function(context) {//I've tried to override this but doesn't work
var value = context.dataset.data[context.dataIndex];
var label = context.label[context.dataIndex];
return label+' '+value;
},
}
},
},
responsive: true,
}
});

最佳答案

您可以为此使用自定义 generateLabels 函数:

var options = {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
}]
},
options: {
plugins: {
legend: {
labels: {
generateLabels: (chart) => {
const datasets = chart.data.datasets;
return datasets[0].data.map((data, i) => ({
text: `${chart.data.labels[i]} ${data}`,
fillStyle: datasets[0].backgroundColor[i],
}))
}
}
}
}
}
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

关于javascript - ChartJS 在图例中显示值 (Chart.js V3.5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69370149/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com