[javascript] Parcel에서 파이 차트 라이브러리를 사용하는 방법은?

D3.js는 강력한 데이터 시각화 라이브러리로서, 다양한 차트 유형을 지원합니다. Chart.js는 사용하기 쉬운 차트 라이브러리로서, 다양한 차트 유형을 간단하게 구현할 수 있습니다. 이 둘 중 선택하여 파이 차트를 구현할 수 있습니다.

파셀에서 D3.js와 Chart.js를 사용하기 위해서는 다음 단계를 따르세요.

  1. 프로젝트 폴더에서 터미널을 열고 다음 명령어로 Parcel을 설치하세요.
npm install -g parcel-bundler
  1. 프로젝트 폴더에 index.html 파일을 생성하고, 다음 내용을 추가하세요.
<!DOCTYPE html>
<html>
<head>
  <title>파이 차트</title>
  <!-- D3.js 라이브러리 -->
  <script src="https://d3js.org/d3.v6.min.js"></script>
  <!-- Chart.js 라이브러리 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <!-- 파이 차트를 보여줄 canvas 요소 -->
  <canvas id="pie-chart"></canvas>

  <script src="script.js"></script>
</body>
</html>
  1. 프로젝트 폴더에 script.js 파일을 생성하고, 다음 내용으로 파이 차트를 구현하세요.
// D3.js를 사용한 파이 차트
function createD3PieChart() {
  // 데이터
  const data = [10, 20, 30, 40];

  // SVG 요소 크기 설정
  const width = 400;
  const height = 400;
  const radius = Math.min(width, height) / 2;

  // 색상 지정
  const color = d3.scaleOrdinal(d3.schemeCategory10);

  // 파이 차트 생성
  const pie = d3.pie()
    .value(d => d);

  // SVG 요소 생성
  const svg = d3.select("#pie-chart")
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", `translate(${width/2},${height/2})`);

  // 파이 차트 그리기
  const path = svg.selectAll("path")
    .data(pie(data))
    .enter()
    .append("path")
    .attr("d", d3.arc()
      .innerRadius(0)
      .outerRadius(radius)
    )
    .attr("fill", (d, i) => color(i));
}

// Chart.js를 사용한 파이 차트
function createChartJsPieChart() {
  // 데이터
  const data = {
    labels: ["A", "B", "C", "D"],
    datasets: [{
      data: [10, 20, 30, 40],
      backgroundColor: ["red", "green", "blue", "yellow"],
    }]
  };

  // 차트 생성
  new Chart(document.getElementById("pie-chart"), {
    type: "pie",
    data: data,
    options: {}
  });
}

// 파이 차트 생성 함수 호출
createD3PieChart();
//createChartJsPieChart();
  1. 터미널에서 다음 명령어로 프로젝트를 실행하세요.
parcel index.html
  1. 웹 브라우저에서 http://localhost:1234로 접속하면 파이 차트를 확인할 수 있습니다.

위 코드에서 createD3PieChart() 함수는 D3.js를 사용하여 파이 차트를 구현하고, createChartJsPieChart() 함수는 Chart.js를 사용하여 파이 차트를 구현합니다. 원하는 대로 함수를 선택하여 사용하세요.

D3.js와 Chart.js를 활용하여 파이 차트를 구현하는 방법을 알아보았습니다. Parcel을 사용하여 간편하게 프로젝트를 설정하고 차트 라이브러리를 사용할 수 있습니다.