# 라인 차트에서 데이터셋 , 데이터 제거


# 결과화면


# 데이터 제거 버튼 

// 첫번째 값 제거
document.getElementById('firstRemoveData').addEventListener('click', function () {
	// 모든 차트 순회하기 위한 KEY 값 배열
	var keys = Object.keys(Chart.instances);
	// 차트 순회하기 
	keys.forEach(elem => {
		// 데이터 값 세팅
		console.log(Chart.instances[elem].config.data);
		Chart.instances[elem].config.data.labels.shift(); 
		Chart.instances[elem].config.data.datasets.forEach(function (dataset) {
			// 첫번쨰 배열값 제거
			dataset.data.shift();
		});
		// 데이터 업데이트 
		Chart.instances[elem].update();
	});
});

// 마지막 값 제거 
document.getElementById('LastRemoveData').addEventListener('click', function () {
	// 모든 차트 순회하기 위한 KEY 값 배열
	var keys = Object.keys(Chart.instances);
	// 차트 순회하기 
	keys.forEach(elem => {
		// 데이터 값 세팅
		console.log(Chart.instances[elem].config.data);
		Chart.instances[elem].config.data.labels.pop(); 
		Chart.instances[elem].config.data.datasets.forEach(function (dataset) {
			// 마지막 배열값 제거
			dataset.data.pop();
		});
		// 데이터 업데이트 
		Chart.instances[elem].update();
	});
});

# 데이터셋 제거 버튼

document.getElementById('FirstRemoveDataset').addEventListener('click', function () {
	// 모든 차트 순회하기 위한 KEY 값 배열
	var keys = Object.keys(Chart.instances);
	// 차트 순회하기 
	keys.forEach(elem => {
		// 데이터 값 세팅
		console.log(Chart.instances[elem].config.data);
		// 첫번째 그래프 제거
		Chart.instances[elem].config.data.datasets.pop();
		// 데이터 업데이트 
		Chart.instances[elem].update();
	});
});

document.getElementById('LastRemoveDataset').addEventListener('click', function () {
	// 모든 차트 순회하기 위한 KEY 값 배열
	var keys = Object.keys(Chart.instances);
	// 차트 순회하기 
	keys.forEach(elem => {
		// 데이터 값 세팅
		console.log(Chart.instances[elem].config.data);
		// 마지막 그래프 제거
		Chart.instances[elem].config.data.datasets.shift();
		// 데이터 업데이트 
		Chart.instances[elem].update();
	});
});

 

블로그 이미지

미나미나미

,

# 라인 차트 생성 후,  여러 차트에 데이터셋 , 데이터 추가 방법


 

 

#결과화면


# 데이터셋 추가 버튼

var colorNames = Object.keys(window.chartColors);
// chartColor는 아래 차트 옵션에 정의되어 있음
// 데이터셋 추가 버튼 
document.getElementById('addDataset').addEventListener('click', function () {
	var colorNames = Object.keys(window.chartColors);
	// 새로운 데이터셋 세팅 
	var newData = {
		// 라벨 
		label: 'Dataset',
		// 꼭지점
		backgroundColor: '',
		// 라인색 
		borderColor: '',
		data: [],
	};

	var fill = [
		'end',
		'start', 
		'origin', 
		false 
	];

	for (let index = 0; index < 4; index++) {
		// 데이터 세팅 
		var settingData = JSON.parse(JSON.stringify(newData));
		// 배경
		settingData.backgroundColor = chartColors[colorNames[index + 1]];
		// 선색
		settingData.borderColor = chartColors[colorNames[index + 2]];
		// 라벨
		settingData.label = 'new Data line' + (index + 1) + '/ Fill=' + fill[index];
		// 채우기 옵션
		settingData.fill = fill[index];
		// 데이터 채우기 
		for(var i = 0; i < Chart.instances[0].config.data.datasets[0].data.length; i++){
			settingData.data.push(randomScalingFactor());
		}
		// 데이터 반영 
		Chart.instances[index].data.datasets.push(settingData);
		// 라인 차트 업데이트 
		Chart.instances[index].update();
	}
});

# 데이터 추가 버튼

// 데이터 추가 버튼 
document.getElementById('addData').addEventListener('click', function() {
	// 모든 차트 순회하기 위한 KEY 값 배열
	var keys = Object.keys(Chart.instances);
	// 차트 순회하기 
	keys.forEach(elem => {
		// 차트 옵션의 달력 값 지정 
		var month = MONTHS[Chart.instances[elem].config.data.labels.length % MONTHS.length];
		// 차트 키 값  
		// console.log(elem);
		// 달력값 
		// console.log(month);
		// 차트 객체 
		// console.log(Chart.instances[elem]);
		// 차트 객체의 달력값 (라벨 지정)
		Chart.instances[elem].config.data.labels.push(month);
		// 데이터 값 세팅 
		Chart.instances[elem].config.data.datasets.forEach(function(dataset) {
			dataset.data.push(randomScalingFactor());
		});
		// 데이터 업데이트 
		Chart.instances[elem].update();
	});
});

# 차트 생성 옵션 

// 차트에 표현할 x 축의 값
var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
// 차트에 표현할 컬러 
var chartColors = {
	red: 'rgb(255, 99, 132)',
	orange: 'rgb(255, 159, 64)',
	yellow: 'rgb(255, 205, 86)',
	green: 'rgb(75, 192, 192)',
	blue: 'rgb(54, 162, 235)',
	purple: 'rgb(153, 102, 255)',
	grey: 'rgb(201, 203, 207)'
};
var config = {
	type: 'line',
	data: {
		labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
		datasets: []
	},
	options: {
		// 컨테이너가 수행 할 때 차트 캔버스의 크기를 조정(dafalut : true)
		responsive: true,
		// 크기 조정 이벤트 후 새 크기로 애니메이션하는 데 걸리는 시간(밀리 초) (defalut : 0)
		responsiveAnimationDuration: 1000,
		// (width / height) 크기를 조정할 떄 원래 캔버스 종횡비를 유지 (defalut : true)
		maintainAspectRatio: true,
		// 캔버스 종횡비( width / height, 정사각형 캔버스를 나타내는 값) 높이가 속성으로 또는 스타일 통해 명시적으로 정의된 경우이 옵션은 무시
		aspectRatio: 2,
		// 크기 조정이 발생할 때 호출
		onResize: function () {
			console.log('onResize');
		},
		title: {
			display: true,
			// 차트 제목 
			text: 'Chart.js Line Chart'
		},
		tooltips: {
			mode: 'index',
			intersect: false,
		},
		hover: {
			mode: 'nearest',
			intersect: true
		},
		scales: {
			x: {
				display: true,
				scaleLabel: {
					display: true,
					labelString: 'Month'
				}
			},
			y: {
				display: true,
				scaleLabel: {
					display: true,
					labelString: 'Value'
				}
			}
		}
	}
};

// -100 ~ 100 사이 랜덤값 생성 
var randomScalingFactor = function () {
	return Math.round(Samples.utils.rand(-100, 100));
};
// 새로운 데이터 만들기 
var datasetSample = {
	label: 'label',
	backgroundColor: window.chartColors.red,
	borderColor: window.chartColors.red,
	data: [
		randomScalingFactor(),
		randomScalingFactor(),
		randomScalingFactor(),
		randomScalingFactor(),
		randomScalingFactor(),
		randomScalingFactor(),
		randomScalingFactor()
	],
};

 

블로그 이미지

미나미나미

,

   # chart.js Fill 옵션 정리 

    - Fill 옵션은 총 네 가지가 존재합니다 

    - false  : 아무것도 채워지지 않음

    - origin : 기준점 사이로 채워짐 

    - start : x축 선부터 채워짐

    - end : x축의 최대값의 기준으로 채워짐


   # chart 생성 옵션

var config = {
			type: 'line',
			data: {
				labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
				datasets: []
			},
			options: {
				// 컨테이너가 수행 할 때 차트 캔버스의 크기를 조정(dafalut : true)
				responsive: true,
				// 크기 조정 이벤트 후 새 크기로 애니메이션하는 데 걸리는 시간(밀리 초) (defalut : 0)
				responsiveAnimationDuration: 1000,
				// (width / height) 크기를 조정할 떄 원래 캔버스 종횡비를 유지 (defalut : true)
				maintainAspectRatio: true,
				// 캔버스 종횡비( width / height, 정사각형 캔버스를 나타내는 값) 높이가 속성으로 또는 스타일 통해 명시적으로 정의된 경우이 옵션은 무시
				aspectRatio: 2,
				// 크기 조정이 발생할 때 호출
				onResize: function () {
					console.log('onResize');
				},
				title: {
					display: true,
					// 차트 제목 
					text: 'Chart.js Line Chart'
				},
				tooltips: {
					mode: 'index',
					intersect: false,
				},
				hover: {
					mode: 'nearest',
					intersect: true
				},
				scales: {
					x: {
						display: true,
						scaleLabel: {
							display: true,
							labelString: 'Month'
						}
					},
					y: {
						display: true,
						scaleLabel: {
							display: true,
							labelString: 'Value'
						}
					}
				}
			}
		};

   # chart 데이터 셋 생성

	// -100 ~ 100 사이 랜덤값 생성 
		var randomScalingFactor = function () {
			return Math.round(Samples.utils.rand(-100, 100));
		};
		// 새로운 데이터 만들기 
		var datasetSample = {
			label: 'label',
			backgroundColor: window.chartColors.red,
			borderColor: window.chartColors.red,
			data: [
				randomScalingFactor(),
				randomScalingFactor(),
				randomScalingFactor(),
				randomScalingFactor(),
				randomScalingFactor(),
				randomScalingFactor(),
				randomScalingFactor()
			],
		};

# chart 생성하기

// line1 ========================================================
// 생성할 canvas 요소 
var line1 = document.getElementById('line1').getContext('2d');
// config 파일 복사
var line1Config = JSON.parse(JSON.stringify(config));

// 데이터셋 생성하기 
var line1DatasetSample = datasetSample;
/// 라벨 
line1DatasetSample.label = 'line1 Dataset Sample';
// 채우기 옵션 
line1DatasetSample.fill = false;
// 채웠을 때 색깔
line1DatasetSample.backgroundColor = window.chartColors.red;
// 선 색깔 
line1DatasetSample.borderColor = window.chartColors.yellow;
// 데이터 채우기 
line1Config.data.datasets.push(line1DatasetSample);
// 타이틀값 
line1Config.options.title.text = 'line1/Fill Option = false';
// 차트 생성하기
window.line1 = new Chart(line1, line1Config);
//  ======================================================== line1

# 결과화면


 

블로그 이미지

미나미나미

,

# [charts.js]  intersection 이해하기 

   - charts.js의 제공하는 샘플 코드가 잘되어있어서 주석을 넣었습니다.

   - 아래의 jsffidle 화면을 통해서 비교해서 모드와 intersection을 선택하여 사용하시면 좋을것 같습니다.


 

 

# intersection 사용법 

options: {
	responsive: true,
	title: {
		display: true,
		text: 'Mode: ' + mode + ', intersect = ' + intersect
	},
	tooltips: {
        // 툴팁을 표현하는 방법
        // index, dataset, point, nearest(defalut), x, y
		mode: mode,
        // 툴팁을 표현할 때, 근처일때 표현할 것인가 아닌가
        // true(defalut), false
		intersect: intersect,
	},
	hover: {
		mode: mode,
		intersect: intersect
	},
}

 # intersection 사용한 화면

    - mode와 interesection의 사용법에 따라서 툴팁의 표현이 다릅니다.


 # 전체 테스트 코드

( # charts.js에서 utils.js는 cdn으로 제공하지 않아서 같이 들어가 있습니다. 이점 참고하세요.)

더보기

<!doctype html>

<html>

 

<head>

    <title>Tooltip Interaction Modes</title>

    <!-- <script src="../../dist/chart.min.js"></script> -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js" integrity="sha512-QEiC894KVkN9Tsoi6+mKf8HaCLJvyA6QIRzY5KrfINXYuP9NxdIkRQhGq3BZi0J4I7V5SidGM3XUQ5wFiMDuWg==" crossorigin="anonymous"></script>

    <!-- <script src="../../utils.js"></script> -->

 

<style>

        canvas {

            -moz-user-selectnone;

            -webkit-user-selectnone;

            -ms-user-selectnone;

        }

 

        .chart-container {

            width400px;

            margin-left10px;

            margin-right10px;

            margin-bottom10px;

            border : 1px solid black;

        }

 

        .container {

            displayflex;

            flex-directionrow;

            flex-wrapwrap;

            justify-contentcenter;

        }

    </style>

</head>

 

<body>

    <div class="container"> </div>

    <script>

        var charts = [];

 

        // 차트 생성하기

        function createConfig(modeintersect) {

            return {

                // 차트 타입

                type: 'line',

                // 데이터셋 

                data: {

                    labels: ['January''February''March''April''May''June''July'],

                    datasets: [{

                        label: 'My First dataset',

                        borderColor: window.chartColors.red,

                        backgroundColor: window.chartColors.red,

                        data: [10304628500],

                        fill: false,

                    }, {

                        label: 'My Second dataset',

                        borderColor: window.chartColors.blue,

                        backgroundColor: window.chartColors.blue,

                        data: [7494613253022],

                        fill: false,

                    }]

                },

                // 옵션

                options: {

                    responsive: true,

                    title: {

                        display: true,

                        text: 'Mode: ' + mode + ', intersect = ' + intersect

                    },

                    tooltips: {

                        mode: mode,

                        intersect: intersect,

                    },

                    hover: {

                        mode: mode,

                        intersect: intersect

                    },

                }

            };

        }

 

        window.onload = function () {

            var container = document.querySelector('.container');

            // mode : defalut 'nearest' (툴팁에 표시되는 요소를 설정)

            // intersect : defalut true || false (마우스 위치가 차트의 항목과 교차할 때 만 호보)

            // axis : 

            // animationDuration : 호버 스타일 변경을 애니메이션하는 데 걸리는 시간 (밀리 초)

            [{

                mode: 'index',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'index',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'dataset',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'dataset',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'point',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'point',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'nearest',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'nearest',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'x',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'x',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'y',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'y',

                intersect: false,

                animationDuration: 300

            }].forEach(function (details) {

                console.log('details'details);

                // div 생성. <div class='chart-container'> </div> 

                var div = document.createElement('div');

                div.classList.add('chart-container');

 

                // canvas 생성.

                var canvas = document.createElement('canvas');

                div.appendChild(canvas);

                container.appendChild(div);

 

                // 2d 렌더링 컨텍스트를 나타내는 CanvasRenderingContext2D 객체를 생성하게 합니다.

                var ctx = canvas.getContext('2d');

                var config = createConfig(details.modedetails.intersect);

                charts.push(new Chart(ctxconfig));

            });

        };

    </script>

 

    <script>

        // charts.js에서 제공하는 utils.js 

        'use strict';

 

window.chartColors = {

    red: 'rgb(255, 99, 132)',

    orange: 'rgb(255, 159, 64)',

    yellow: 'rgb(255, 205, 86)',

    green: 'rgb(75, 192, 192)',

    blue: 'rgb(54, 162, 235)',

    purple: 'rgb(153, 102, 255)',

    grey: 'rgb(201, 203, 207)'

};

 

(function(global) {

    var MONTHS = [

        'January',

        'February',

        'March',

        'April',

        'May',

        'June',

        'July',

        'August',

        'September',

        'October',

        'November',

        'December'

    ];

 

    var COLORS = [

        '#4dc9f6',

        '#f67019',

        '#f53794',

        '#537bc4',

        '#acc236',

        '#166a8f',

        '#00a950',

        '#58595b',

        '#8549ba'

    ];

 

    var Samples = global.Samples || (global.Samples = {});

    var Color = Chart.helpers.color;

 

    function applyDefaultNumbers(config) {

        var cfg = config || {};

        cfg.min = cfg.min || 0;

        cfg.max = cfg.max || 1;

        cfg.from = cfg.from || [];

        cfg.count = cfg.count || 8;

        cfg.decimals = cfg.decimals || 8;

        cfg.continuity = cfg.continuity || 1;

 

        return cfg;

    }

 

    Samples.utils = {

        // Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/

        srand: function(seed) {

            this._seed = seed;

        },

 

        rand: function(minmax) {

            var seed = this._seed;

            min = min === undefined ? 0 : min;

            max = max === undefined ? 1 : max;

            this._seed = (seed * 9301 + 49297) % 233280;

            return min + (this._seed / 233280) * (max - min);

        },

 

        numbers: function(config) {

            var cfg = applyDefaultNumbers(config);

            var dfactor = Math.pow(10cfg.decimals) || 0;

            var data = [];

            var ivalue;

 

            for (i = 0i < cfg.count; ++i) {

                value = (cfg.from[i] || 0) + this.rand(cfg.mincfg.max);

                if (this.rand() <= cfg.continuity) {

                    data.push(Math.round(dfactor * value) / dfactor);

                } else {

                    data.push(null);

                }

            }

 

            return data;

        },

 

        labels: function(config) {

            var cfg = config || {};

            var min = cfg.min || 0;

            var max = cfg.max || 100;

            var count = cfg.count || 8;

            var step = (max - min) / count;

            var decimals = cfg.decimals || 8;

            var dfactor = Math.pow(10decimals) || 0;

            var prefix = cfg.prefix || '';

            var values = [];

            var i;

 

            for (i = mini < maxi += step) {

                values.push(prefix + Math.round(dfactor * i) / dfactor);

            }

 

            return values;

        },

 

        months: function(config) {

            var cfg = config || {};

            var count = cfg.count || 12;

            var section = cfg.section;

            var values = [];

            var ivalue;

 

            for (i = 0i < count; ++i) {

                value = MONTHS[Math.ceil(i) % 12];

                values.push(value.substring(0section));

            }

 

            return values;

        },

 

        color: function(index) {

            return COLORS[index % COLORS.length];

        },

 

        transparentize: function(coloropacity) {

            var alpha = opacity === undefined ? 0.5 : 1 - opacity;

            return Color(color).alpha(alpha).rgbString();

        }

    };

 

    // DEPRECATED

    window.randomScalingFactor = function() {

        return Math.round(Samples.utils.rand(-100100));

    };

 

    // INITIALIZATION

 

    Samples.utils.srand(Date.now());

 

    // Google Analytics

    /* eslint-disable */

    if (document.location.hostname.match(/^(www\.)?chartjs\.org$/)) {

        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){

        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)

        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create''UA-28909194-3''auto');

        ga('send''pageview');

    }

    /* eslint-enable */

 

}(this));

 

    </script>

</body>

 

</html>

블로그 이미지

미나미나미

,