취업/Chart.js

[Chart.JS]Line Chart Boundaries 라벨붙이기

카슈밀 2022. 10. 25. 15:13
반응형
const ctx = document.getElementById('lineGraph').getContext('2d');
let gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(25, 224, 167, 1)');   
gradient.addColorStop(1, 'rgba(25, 224, 167, 0)');

const lineData = {
    labels: ['', "January", "February", "March", "April", "May", "June", "July", ''],
    datasets: [
        {
            label: 'Dataset',
            data: [, 5, 20, 45, 50, 60, 80, 150],
            backgroundColor : gradient,
            fill: true,
            borderColor : "#19E0A7",
        }
    ]
};

const lineConfig = {
    type: 'line',
    data: lineData,
    plugins:[ChartDataLabels],
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            x: {
                ticks: {
                    display: false //this will remove only the label
                },
                grid: {
                    borderDash:  [6, 4],
                    borderDashOffset: 1,
                    color: function (context) {
                        if (context.tick.value === 0) {
                            return 'rgba(0, 0, 0, 0)';
                        }
                        return 'rgba(0, 0, 0, 0.1)';
                    },
                }
            },
            y: {
                grid: {
                    borderDash:  [6, 4],
                    borderDashOffset: 2,
                    color: function (context) {
                        if (context.tick.value === 0) {
                            return 'rgba(0, 0, 0, 0)';
                        }
                        return 'rgba(0, 0, 0, 0.1)';
                    },
                }
            },
        },
        plugins: {
            legend:{
                display:false
            },
            animation: {
                duration: 0,
            },
            tooltip: {
                enabled: false
            },
            datalabels: {
                anchor: 'top',
                align: 'top',
                formatter: function (value, context) {
                    if (context.dataIndex == context.dataset.data.length - 1)
                    {
                        return [value + " %"];
                    } else if (context.dataIndex == 1) {
                        return [value + " %"];
                    } else {
                        return value;
                    }
                },
                font: {
                    weight: 'bold',
                    size: '12px',
                },
                color: '474747',
            },
            scaleShowLabelBackdrop : true,
            showAllTooltips : true,
        },
        interaction: {
            intersect: false,
        },
    },

};

const lineGraph = new Chart($('#lineGraph'), lineConfig);

적용 끝.

728x90