Angular - ChartJS -条形图-第一个标签未显示在X轴中

r3i60tvu  于 2023-04-06  发布在  Chart.js
关注(0)|答案(1)|浏览(151)

我尝试使用chartJS和Angular绘制一个条形图。为此,我对X轴值进行分组,以便它只显示年份。

但是我每次都错过了第一年。这意味着在上面的场景中,我有2022年和2023年的记录,但图表只显示2023年。
这种行为背后的原因是我没有2022年1月1日的数据。但我需要将2022也作为X轴的标签。我已经尝试添加bounds: 'ticks',但它在左侧和右侧显示空白(考虑到2022年的第一天)

是否有任何选项显示标签不包括空格?任何帮助,你可以提供将不胜感激。

xoshrz7s

xoshrz7s1#

一个可能的解决方案是将time.unit设置为"month",并使用ticks.callback使每年除第一个标签外的所有标签无效(return '')。
下面是一个非React代码片段,它说明了这个想法:

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>

相关问题