ChartJS 3+x轴仅显示完整的时刻对象,而不是仅显示月份 [英] ChartJS 3+ x-axis only showing full moment object instead of just month
本文介绍了ChartJS 3+x轴仅显示完整的时刻对象,而不是仅显示月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用Momentjs在图表的x轴上仅显示月份和年份,但它只将看似完整的时刻日期放在x轴上。
我看过很多这样做的示例,但似乎没有一个在最新版本的chartjs中起作用。 我知道与Momentjs配合使用所需的适配器(&Q;),但无法知道它是否工作。
这里是我正在使用的代码的jsfiddle,非常感谢您的帮助。https://jsfiddle.net/7z20jg68/
我告诉我Invalid scale configuration for scale: x
也有错误,这很混乱,因为我的x轴似乎顺序正确。谢谢!
推荐答案
您的X轴刻度确实无效,您将其声明为V2语法的数组,在V3中,所有刻度都是它们自己的对象,其中对象的键是scaleID。因此,删除x轴缩放对象周围的数组括号将解决此问题。
还有您的图例和工具提示配置(在错误的位置和错误的位置),还有V2语法。
有关所有更改,请阅读migration guide
const gainedChart = document.getElementById('gained-chart').getContext('2d');
const gain = [74.699997, 76.580002, 81.349998, 83.000000, 85.879997, 83.120003, 77.989998, 81.279999];
const dates = ["Jan 2, 20", "Feb 3, 20", "Mar 4, 20", "Apr 5, 20", "May 6, 20", "Jun 9, 20", "Nov 10, 20", "Dec 11, 20"];
let gainData = {
datasets: [{
label: "Gain (%)",
data: gain,
borderColor: 'rgba(255, 66, 66, 1)',
backgroundColor: 'rgba(255, 66, 66, 1)',
pointRadius: 1.2,
pointBackgroundColor: 'rgba(255, 66, 66, 0.8)',
pointHoverRadius: 6,
pointHitRadius: 20,
pointBorderWidth: 2,
}]
};
let gainConfig = {
plugins: {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
color: 'black'
},
},
tooltip: {
callbacks: {
label: function(tooltipItem, data) {
return parseInt(tooltipItem.parsed.y)
}
}
},
},
scales: {
x: {
type: 'time',
time: {
minUnit: 'month'
}
},
y: {
suggestedMax: 45,
ticks: {
stepSize: 5,
//max: 100
},
},
},
maintainAspectRatio: false,
responsive: true,
};
let lineGainChart = new Chart(gainedChart, {
type: 'line',
data: gainData,
options: gainConfig,
plugins: [{
beforeInit: function(lineGainChart) {
for (let c = 0; c < dates.length; c++) {
let myMoment = moment(dates[c], 'MMM D, YYYY');
lineGainChart.data.labels.push(myMoment);
}
}
}]
});
<canvas class="graph-canvas" id="gained-chart" width="400" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
这篇关于ChartJS 3+x轴仅显示完整的时刻对象,而不是仅显示月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文