CHART.JS 사용법 정리

CDN으로 가져오기 

<script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>

<canvas id="myChart"></canvas>

차트 ID 부여하기

const ctx = document.getElementById('myChartex').getContext('2d');

data 랑 options를 만드세요. 하나로 해도 되지만 {} 너무 많아서 눈이 어지러운 것 같아요. 

const _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
        }]
    };
const _options=
{
    	    indexAxis: 'y',
    	    // Elements options apply to all of the options unless overridden in a dataset
    	    // In this case, we are setting the border of each horizontal bar to be 2px wide
    	    elements: {
    	      bar: {
    	        borderWidth: 2,
    	      }
    	    },
    	    responsive: true,
    	    plugins: {
    	      legend: {
    	        position: 'right',
    	      },
    	      title: {
    	        display: true,
    	        text: 'Chart.js Horizontal Bar Chart'
    	      }
    	    }
    	};

차트를 생성한다. 차트의 형태에 따라 options값을 달리하면 된다.

chart = new Chart(ctx, {
          type: 'bar', // 차트의 형태
          data : lineChartData,
          options : options
         });

차트데이터

차트를 표시해 보았네요.

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,