gpt4 book ai didi

javascript - Chart.js - 千位分隔符、工具提示中的货币、X 和 Y 轴标签

转载 作者:行者123 更新时间:2023-11-28 17:34:20 25 4
gpt4 key购买 nike

我是 Chart.js 的新手,我一直在尝试将我发现的所有代码片段一起工作,以使我的标签和工具提示正确显示。我想我应该发布我的工作脚本来展示我如何设法使用千位分隔符显示我的值,将货币符号添加到工具提示和刻度,并在 X 和 Y 轴上添加标签。我看到的一些帖子没有关于在哪里放置相关代码的示例。

请注意,我没有编写所有这些代码。这是通过多次堆栈搜索和多次尝试编译的,以使其中一些能够协同工作。

最佳答案

这是我使用的代码...

    <canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["July", "August", "September", "October", "November", "December", "January", "February", "March", "April", "May", "June"],
datasets: [{
label: 'YTD 2017/18',
data: ["12000, 11250, 10000, 2000, 3000, 6000,12000, 11250, 10000, 2000, 3000, 6000"],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Total Sales',
fontStyle: 'bold',
fontSize: 20
},
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
if(parseInt(value) >= 1000){
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Months of the Year',
fontStyle: 'bold',
fontSize: 20
}
}],
},
tooltips: {
callbacks: {
// this callback is used to create the tooltip label
label: function(tooltipItem, data) {
// get the data label and data value to display
// convert the data value to local string so it uses a comma seperated number
var dataLabel = data.labels[tooltipItem.index];
// add the currency symbol $ to the label
var value = ': $ ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
// make sure this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
if (Chart.helpers.isArray(dataLabel)) {
// show value on first line of multiline label
// need to clone because we are changing the value
dataLabel = dataLabel.slice();
dataLabel[0] += value;
} else {
dataLabel += value;
}
// return the text to display on the tooltip
return dataLabel;
}
}
},
}
});
</script>

关于javascript - Chart.js - 千位分隔符、工具提示中的货币、X 和 Y 轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49491046/

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