본문 바로가기
개발이야기/Etc.

chart.js 로 그래프 그리기

by hyung12 2019. 4. 11.
반응형

chart.js 를 활용하여 그래프를 그리는 작업을 했다.

(chart.js 링크: https://www.chartjs.org/)

 

기본 bar 그래프를 사용하면 좋으려만 디자인은 그렇게 나오지 않았기에.....

그리하여 이번에 작업하면서 사용했던 코드를 끄적여 보려 함~

 


설치

 

GitHub 릴리즈에서 최신 버전 다운로드: https://github.com/chartjs/Chart.js/releases/tag/v2.8.0

CDN 사용: https://www.jsdelivr.com/package/npm/chart.js

npm 또는 bower로 설치: https://www.chartjs.org/docs/latest/getting-started/installation.html

 

이 중에서 하나를 택하여 설치하면 되는데 나는 CDN을 사용!

 


Bar 차트 만들기

 

[HTML]

<canvas id="myChart" width="400" height="400"></canvas>

 

[JS]

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

 

[RESULT]

 


툴팁 커스텀 차트

 

[HTML]

<canvas id="chartDefult"></canvas>

 

[JS]

var ctx = document.getElementById('chartTooltipCustom').getContext('2d');
var chartTooltipCustom = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        datasets: [{
            label: 'Chart Graph',
            backgroundColor: 'rgba(183, 183, 183, 0.6)',
            data: [0, 10, 56, 91, 20, 30, 45, 70, 82, 33, 61, 38]
        }]
    },
    options: {
        responsive: true,
        legend: {
            display: false,
        },
        scales: {
            yAxes: [{
                ticks: {
                    min: 0,
                    max: 100,
                    stepSize: 20,
                },
            }],
        },
        tooltips: {
            displayColors: false, // 툴팁 바 컬러 표시 여부
            backgroundColor: '#0a6dff', // 툴팁 배경
            titleFontColor: '#fff', // 툴팁 폰트 관련
            titleAlign: 'center', // 툴팁 폰트 관련
            bodySpacing: 2, // 툴팁 폰트 관련
            bodyFontColor: '#fff', // 툴팁 폰트 관련
            bodyAlign: 'center', // 툴팁 폰트 관련
            footerFontStyle: 'bold', // 툴팁 폰트 관련
            footerFontColor: '#fff', // 툴팁 폰트 관련
            footerAlign: 'center', // 툴팁 폰트 관련
            callbacks: {
                label: function(tooltipItem, data) {
                return data['labels'][tooltipItem['index']] + ": " + data['datasets'][0]['data'][tooltipItem['index']];
                },
            }
        },
    }
});

 

[RESULT]

 

 


모든 툴팁 고정 차트

 

[HTML]

<canvas id="chartTooltipCustom"></canvas>

 

[JS]

var ctx = document.getElementById('chartFixedTooltips').getContext('2d');
Chart.plugins.register({
    beforeRender: function (chart) {
        if (chart.config.options.showAllTooltips) {
            // create an array of tooltips
            // we can't use the chart tooltip because there is only one tooltip per chart
            chart.pluginTooltips = [];
            chart.config.data.datasets.forEach(function (dataset, i) {
                chart.getDatasetMeta(i).data.forEach(function (sector, j) {
                    chart.pluginTooltips.push(new Chart.Tooltip({
                        _chart: chart.chart,
                        _chartInstance: chart,
                        _data: chart.data,
                        _options: chart.options.tooltips,
                        _active: [sector]
                    }, chart));
                });
            });

            // turn off normal tooltips
            chart.options.tooltips.enabled = false;
        }
    },
    afterDraw: function (chart, easing) {
        if (chart.config.options.showAllTooltips) {
            // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
            if (!chart.allTooltipsOnce) {
                if (easing !== 1)
                    return;
                chart.allTooltipsOnce = true;
            }

            // turn on tooltips
            chart.options.tooltips.enabled = true;
            Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
                tooltip.initialize();
                tooltip.update();
                // we don't actually need this since we are not animating tooltips
                tooltip.pivot();
                tooltip.transition(easing).draw();
            });
            chart.options.tooltips.enabled = false;
        }
    }
});
var chartFixedTooltips = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        datasets: [{
            label: 'Chart Graph',
            backgroundColor: 'rgba(183, 183, 183, 0.6)',
            data: [0, 10, 56, 91, 20, 30, 45, 70, 82, 33, 61, 38]
        }]
    },
    animation:{
        animateScale: true,
        animateRotate:true
    },
    options: {
        responsive: true,
        legend: {
            display: false,
        },
        scales: {
            yAxes: [{
                ticks: {
                    min: 0,
                    max: 100,
                    stepSize: 20,
                },
            }],
        },
        scaleShowLabelBackdrop : true,
        showAllTooltips : true,
        tooltips: {
            displayColors: false,
            callbacks: {
                title: function(tooltipItem, data) {
                return;
                },
                label: function(tooltipItem, data) {
                return data['labels'][tooltipItem['index']] + ": " + data['datasets'][0]['data'][tooltipItem['index']];
                },
            }
        },
    }
});

 

[RESULT]

 

 


모든 데이터 고정 차트

 

[HTML]

<canvas id="chartFixedTooltips"></canvas>

 

[JS]

var ctx = document.getElementById('chartFixedData').getContext('2d');
var chartFixedData = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        datasets: [{
            label: 'Chart Graph',
            backgroundColor: 'rgba(183, 183, 183, 0.6)',
            data: [0, 10, 56, 91, 20, 30, 45, 70, 82, 33, 61, 38]
        }]
    },
    options: {
        responsive: true,
        legend: {
            display: false,
        },
        scales: {
            yAxes: [{
                ticks: {
                    min: 0,
                    max: 100,
                    stepSize: 20,
                },
            }],
        },
        layout: {
            padding: {
                top: 20,
            }
        },
        tooltips: {
            enabled: false,
        },
        hover: {
            animationDuration: 0
        },
        animation: {
            duration: 1,
            onComplete: function() {
                var chartInstance = this.chart,
                ctx = chartInstance.ctx;

                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';

                this.data.datasets.forEach(function(dataset, i) {
                    var meta = chartInstance.controller.getDatasetMeta(i);
                    meta.data.forEach(function(bar, index) {
                        var data = dataset.data[index];
                        ctx.fillText(data, bar._model.x, bar._model.y - 5);
                    });
                });
            }
        }
    },
});

 

[RESULT]

 

 


특정 값만 툴팁 노출 고정 차트(특정 색으로 기준 잡음)

 

[HTML]

<canvas id="chartSpecialTooltips"></canvas>

 

[JS]

var ctx = document.getElementById('chartSpecialTooltips').getContext('2d');
Chart.plugins.register({
    beforeRender: function (chart) {
        if (chart.config.options.showAllTooltips) {
            // create an array of tooltips
            // we can't use the chart tooltip because there is only one tooltip per chart
            chart.pluginTooltips = [];
            chart.config.data.datasets.forEach(function (dataset, i) {
                chart.getDatasetMeta(i).data.forEach(function (sector, j) {
                    chart.pluginTooltips.push(new Chart.Tooltip({
                        _chart: chart.chart,
                        _chartInstance: chart,
                        _data: chart.data,
                        _options: chart.options.tooltips,
                        _active: [sector]
                    }, chart));
                });
            });

            // turn off normal tooltips
            chart.options.tooltips.enabled = false;
        }
    },
    afterDraw: function (chart, easing) {
        if (chart.config.options.showAllTooltips) {
            // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
            if (!chart.allTooltipsOnce) {
                if (easing !== 1)
                    return;
                chart.allTooltipsOnce = true;
            }

            // turn on tooltips
            chart.options.tooltips.enabled = true;
            Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
                tooltip.initialize();
                tooltip.update();
                // we don't actually need this since we are not animating tooltips
                tooltip.pivot();
                tooltip.transition(easing).draw();
            });
            chart.options.tooltips.enabled = false;
        }
    }
});
var chartFixedTooltips = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        datasets: [{
            label: 'Chart Graph',
            backgroundColor: [
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(118, 184, 231, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
                'rgba(183, 183, 183, 0.6)',
            ],
            data: [0, 10, 56, 91, 20, 30, 45, 70, 82, 33, 61, 38]
        }]
    },
    animation:{
        animateScale: true,
        animateRotate:true
    },
    options: {
        responsive: true,
        legend: {
            display: false,
        },
        scales: {
            yAxes: [{
                ticks: {
                    min: 0,
                    max: 100,
                    stepSize: 20,
                },
            }],
        },
        layout: {
            padding: {
                top: 20,
            }
        },
        scaleShowLabelBackdrop : true,
        showAllTooltips : true,
        tooltips: {
            displayColors: false,
            filter: function (tooltipItem, data) { // 특정 툴팁 표시
                var backgroundColor = data.datasets[0].backgroundColor[tooltipItem.index];
                if (backgroundColor == 'rgba(118, 184, 231, 0.6)') {
                    return true;
                } else {
                    return false;
                }
            },
            callbacks: {
                title: function(tooltipItem, data) { // 툴팁 타이틀
                    return false;
                },
                label: function(tooltipItem, data) { // 툴팁 라벨
                    var backgroundColor = data.datasets[0].backgroundColor[tooltipItem.index];
                    if (backgroundColor == 'rgba(118, 184, 231, 0.6)') {
                        return data['labels'][tooltipItem['index']] + ": " + data['datasets'][0]['data'][tooltipItem['index']];
                    } else {
                        return false;
                    }
                },
            }
        }
    }
});

 

[RESULT]

 

 

 


chart.js를 통해 다양한 그래프 모양을 만들어봤다.

이보다 더 좋은 코드가 있으면 공유했으면 좋겠다 히힛-

반응형