Chart.js

박경찬·2022년 11월 28일
0

오랜만에 포스팅한다.. 헤헤

이번에는 차트!! 차트를 사용해보려고 한다.
이번 개발업무에 필수로 들어가야 하는 기능이라 기본 사용법을 적어 두려고 한다


  const ctx = document.getElementById('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],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });

기본 코드는 이렇게 시작한다.

>  type : polarArea, scatter,pie , radar,derivedBubble , bar , line
 "바로 보여줄건지 라인으로 보여줄건지! bar , line " 을 많이 쓴다.
 data:{
 	lebels: x 축 정의 ( 보통 시간, 날짜 를 보여준다 )
    datasets: 백엔드에서 받아온 데이터들을 정렬하여 보여준다.
    datasets에서 사용할수 있는 여러가지 옵션들이있다
    (weight,cutout,tension,pointRadius,borderWidth,backgroundColor,data,fill)
      
 }
options: 차트 옵션을 정의 하는곳이다.

실제로 필자는 차트를 정의 하면서 data를 분리하여 작업했다.

  const data_1 = {
    labels: months(7),
    datasets: [
            {
                label: 'today',  
                data:  [65, 59, 80, 81, 56, 55, 40,20,100,50,40,60],
                borderColor: CHART_COLORS.red,
                backgroundColor: CHART_COLORS.red,
                order: 2
            },

            {
                label: 'weeks',
                data:  [30, 40, 20, 70, 36, 45, 40,20,30,50,60,70],
                borderColor: CHART_COLORS.blue,
                backgroundColor: CHART_COLORS.blue,
                type: 'line',
                order: 0
            },

            {
                label: 'months',
                data:  [10, 20, 30, 40, 50, 60, 70,80,90,100,110,120],
                borderColor: CHART_COLORS.orange,
                backgroundColor: CHART_COLORS.orange,
                type: 'line',
                order: 1
            }
        ]
    };

    const config =  new Chart(ctx4,{
        type: 'bar',
        data: data_1,
        options: {
        responsive: true,
        plugins: {
            legend: {
            position: 'top',
            },
            title: {
            display: true,
            text: '조명'
            }
        }
        },
    });

CHART_COLORS 차트js 에서 지원하는 라이브러리 utils 를 이용하여 불러와 사용했다.

utils 파일

// Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
var _seed = Date.now();

export function srand(seed) {
 _seed = seed;
}

export function rand(min, max) {
 min = valueOrDefault(min, 0);
 max = valueOrDefault(max, 0);
 _seed = (_seed * 9301 + 49297) % 233280;
 return min + (_seed / 233280) * (max - min);
}

export function numbers(config) {
 var cfg = config || {};
 var min = valueOrDefault(cfg.min, 0);
 var max = valueOrDefault(cfg.max, 100);
 var from = valueOrDefault(cfg.from, []);
 var count = valueOrDefault(cfg.count, 8);
 var decimals = valueOrDefault(cfg.decimals, 8);
 var continuity = valueOrDefault(cfg.continuity, 1);
 var dfactor = Math.pow(10, decimals) || 0;
 var data = [];
 var i, value;

 for (i = 0; i < count; ++i) {
   value = (from[i] || 0) + this.rand(min, max);
   if (this.rand() <= continuity) {
     data.push(Math.round(dfactor * value) / dfactor);
   } else {
     data.push(null);
   }
 }

 return data;
}

export function points(config) {
 const xs = this.numbers(config);
 const ys = this.numbers(config);
 return xs.map((x, i) => ({x, y: ys[i]}));
}

export function bubbles(config) {
 return this.points(config).map(pt => {
   pt.r = this.rand(config.rmin, config.rmax);
   return pt;
 });
}

export function labels(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(10, decimals) || 0;
 var prefix = cfg.prefix || '';
 var values = [];
 var i;

 for (i = min; i < max; i += step) {
   values.push(prefix + Math.round(dfactor * i) / dfactor);
 }

 return values;
}

const MONTHS = [
 'January',
 'February',
 'March',
 'April',
 'May',
 'June',
 'July',
 'August',
 'September',
 'October',
 'November',
 'December'
];

export function months(config) {
 var cfg = config || {};
 var count = cfg.count || 12;
 var section = cfg.section;
 var values = [];
 var i, value;

 for (i = 0; i < count; ++i) {
   value = MONTHS[Math.ceil(i) % 12];
   values.push(value.substring(0, section));
 }

 return values;
}

const COLORS = [
 '#4dc9f6',
 '#f67019',
 '#f53794',
 '#537bc4',
 '#acc236',
 '#166a8f',
 '#00a950',
 '#58595b',
 '#8549ba'
];

export function color(index) {
 return COLORS[index % COLORS.length];
}

export function transparentize(value, opacity) {
 var alpha = opacity === undefined ? 0.5 : 1 - opacity;
 return colorLib(value).alpha(alpha).rgbString();
}

export const CHART_COLORS = {
 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)'
};

const NAMED_COLORS = [
 CHART_COLORS.red,
 CHART_COLORS.orange,
 CHART_COLORS.yellow,
 CHART_COLORS.green,
 CHART_COLORS.blue,
 CHART_COLORS.purple,
 CHART_COLORS.grey,
];

export function namedColor(index) {
 return NAMED_COLORS[index % NAMED_COLORS.length];
}

export function newDate(days) {
 return DateTime.now().plus({days}).toJSDate();
}

export function newDateString(days) {
 return DateTime.now().plus({days}).toISO();
}

export function parseISODate(str) {
 return DateTime.fromISO(str);
}

utils 파일에는 여러가지 함수들이 있는데 대표적으로 시간 계산식 및 차트 색을 쉽게 꺼내서 사용할수 있다.
피자는 js파일을 만들어 코드를 복붙해서 사용했다.

실제로 차트를 그리고 사용하는건 어렵지 않다. 하지만 생각하지 못한 오류를 봤는데 아직 해결하지 못했다.
오류 : can't acquire context from the given item
이 오류는 2D 그래픽의 경우 .getContext() 사용하여 컨텍스트 타입 을 지정하고 하나의 파라메터를 가지기 때문이다.

document.getElementById("myChart").getContext("2d");

차트를 사용하고 응용하는건 어렵지 않타!! 다행이다!! 표형식이라서 데이터 다루기가 쉽지 않을거 같았는데 막상 해보니 어렵지 않아서 맘이 조금 편해졌다.. ㅋㅋ

입사하자마자 기획부터 참여하게 되다 보니 개발공부를 뒤로 자꾸 미루는거 같아 나한테 미안한다.. ㅋㅋㅋ 열심히 하자.. 제발..

0개의 댓글