我正在嘗試制作一個圖表,該圖表沿 x 軸顯示年份,沿 y 軸顯示美元金額。我終于接近了我正在尋找的東西,但我發現因為 x 坐標是數字,ChartJS 在其中放置了逗號,這多年來看起來真的很奇怪。
經過一番挖掘,我使用了回呼。options.plugin.tooltip.callbacks.label努力讓我洗掉工具提示中的逗號,但是當我options.scales.x[0].ticks.callback嘗試修復底部的標簽時,它不僅不起作用,而且我沒有看到console.log他們曾經列印過的宣告,所以它似乎甚至沒有呼叫回呼。根據我在網上和 Stack Overflow 上找到的內容,我嘗試了幾種如何進行回呼的變體,我認為這與 ChartJS 在不同版本中執行此操作的不同方式相對應。(我使用的是 3.5.1 版。)
然后,我意識到……下面的選項options.scales似乎都沒有任何效果。我更改了最小值、標題、刻度設定(顏色為紅色、回呼等),但沒有任何效果。(這也解釋了為什么我在使用折線圖時遇到問題并且不得不切換到散點圖;顯然type: 'linear'沒有被拾取,當我將它設定為type: 'date'或任何確切的作業時它也沒有做任何不同的事情。)
同時,其他選項喜歡options.showLine或options.elements確實有效果,我看到圖表并且在控制臺中沒有收到任何錯誤。所以,它正在選擇選項,只是忽略了我在options.scales.
以下是相關代碼:
// Sample data added to make this example self-contained
// This is my internal data format
let data = {
"Series1": [ {x: 2001, y: 100 }, {x: 2002, y: 110 }, {x: 2003, y: 107 }, ],
"Series2": [ {x: 2001, y: 107 }, {x: 2002, y: 102 }, {x: 2004, y: 95 }, ],
}
// Define data //////////////////////////////////////////////////////
// I convert data to format ChartJS wants and add a few options
let datasets = [];
for(let label in data) {
let c = colorIterator.next().value
datasets.push({
label: label,
data: data[label],
backgroundColor: c,
borderColor: c,
});
}
// Define options //////////////////////////////////////////////////////
let chartConfig = {
type: 'scatter',
data: { datasets: datasets, },
options: {
title: { display: false },
indexAxis: 'x', responsive: true, maintainAspectRatio: false,
showLine: true,
elements: {
line: { display: true, tension: 0, borderWidth: 1, fill: false, },
point: { radius: 3 }
},
interaction: { mode: 'x', },
scales: {
x: [{
type: 'linear',
min: 1995, max: (new Date()).getFullYear() 1, stepSize: 1,
title: { display: true, text: 'Year' },
ticks: {
display: true,
major: { enabled: true },
color: 'red',
callback: function(value, index, ticks) {
console.log(value);
return Chart.Ticks.formatters.numeric.apply(this, [value, index, ticks])
.replace(",","");
}
}
}],
y: [{
title: { display: true, text: '$' },
ticks: {
display: true,
color: 'red',
},
}],
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if(label) {
let x = context.label.replace(",","");
let y = context.formattedValue;
return 'Year ' x ' "' label '": $' y;
} else { return 'x'; }
},
},
},
},
}
};
// MAKE CHART //////////////////////////////////////////////////////
let mainChart = new Chart(document.getElementById(c.id), chartConfig);
uj5u.com熱心網友回復:
如檔案中所述,比例不是陣列。所有的尺度都是尺度物件中的物件。
因此,您需要將代碼更改為:
options: {
scales: {
x: {
// x options
},
y: {
// y options
},
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/491463.html
標籤:javascript 图表.js
上一篇:在反應路由器dom中使用導航時,函式作為反應子錯誤無效
下一篇:MongDB聚合兩個同名值
