Я пытаюсь построить гистограмму, используя chartJS и Angular. Для этого я группирую значения оси X так, чтобы они отображали только год.
но я пропускаю первый год каждый раз. Это означает, что в приведенном выше сценарии у меня есть записи за 2022 и 2023 годы, но на графике будет отображаться только 2023 год.
Причина такого поведения в том, что у меня нет данных с 1 января 2022 года. Но мне нужно также включить 2022 год в качестве метки на оси X. Я пытался добавить bounds: 'ticks'
, но он показывает пробелы слева и справа (учитывая с первого дня 2022 года)
Есть ли возможность показать метку без пробелов? Любая помощь, которую вы можете предоставить, будет принята с благодарностью.
Одним из возможных решений является установка time.unit
на "month"
и использование
ticks.callback для аннулирования (return ''
) всех меток, кроме первой, для каждого года.
Вот нереагированный фрагмент, иллюстрирующий эту идею:
const nPoints = 366,
t0 = Date.now()-366*24*3600*1000,
dt = 24*3600*1000;
const ctx = document.getElementById('canvasChart').getContext("2d");
let data = Array.from(
{length: nPoints},
(_, i)=>({
datetime: t0 + dt*i,
value: 10+4*Math.sin(i*Math.PI*3/nPoints)+
3*Math.random() + (Math.random() < 0.05 ? 5*Math.random() : 0)
})
);
const yearsWithLabel = [];
const config = {
type: 'bar',
data: {
datasets:[{
data,
borderWidth: 1
}]
},
options: {
parsing: {
xAxisKey: 'datetime',
yAxisKey: 'value'
},
scales:{
x:{
type: 'time',
grid:{
display: false
},
ticks:{
maxRotation: 0,
callback(val, index){
if (index === 0){
yearsWithLabel.splice(0);
}
const date = new Date(val),
yr = date.getFullYear();
if (yearsWithLabel.includes(yr)){
// if there's already a label for this year
return '';
}
yearsWithLabel.push(yr);
// you may want to add the month, otherwise one may think
// the interval between the labels 2022 and 2023 is one year:
// return date.toLocaleDateString(undefined, {year: 'numeric', month: "short"})
return date.toLocaleDateString(undefined, {year: 'numeric'})
}
},
time: {
unit: 'month',
}
}
},
plugins: {
legend:{
display: false
}
}
},
};
new Chart(ctx, config);
<div style = "width:90vw;height:90vh">
<canvas id = "canvasChart" ></canvas>
</div>
<script src = "https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src = "https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script>