Project/[Team]외국인 관광객을 위한 카드 플랫폼

[React] Google Charts API 연동 / 소비 패턴 분석, 주간 소비 리포트 만들기

dbfl9911 2024. 8. 6. 11:28
반응형

https://developers.google.com/chart/interactive/docs/gallery/columnchart?hl=ko

 

시각화: 세로 막대형 차트  |  Charts  |  Google for Developers

SVG 또는 VML을 사용하여 브라우저에서 렌더링된 세로 막대 그래프인 열 차트를 만드는 방법을 알아보세요.

developers.google.com

 

- 구글 차트 api 사용해서 소비 패턴 분석, 주간 소비 리포트 만들기 (아직 백이랑 연동 x) 


- 소비 패턴 분석에 사용할 도넛 차트 만들기

import React from 'react';
import { Chart } from 'react-google-charts';

const MyChart = () => {
    const data = [
        ['Task', 'Hours per Day'],
        ['식비/건강', 11],
        ['금융/공공서비스', 2],
        ['교통', 2],
        ['생활편의', 2],
        ['교육/문화', 7],
        ['관광/여가', 7]
    ];

    const total = data.slice(1).reduce((acc, curr) => acc + curr[1], 0);
    const percentages = data.slice(1).map(row => ({
        name: row[0],
        value: row[1],
        percentage: Math.round((row[1] / total) * 100)
    }));

      // 퍼센트가 높은 순서대로 정렬
      const sortedPercentages = [...percentages].sort((a, b) => b.percentage - a.percentage);

     // 가장 높은 퍼센트를 가진 카테고리 찾기
     const highestCategory = percentages.reduce((max, item) => item.percentage > max.percentage ? item : max, percentages[0]);



    const options = {
        title: '9월 소비패턴 분석',
        pieHole: 0.4,
        slices: {
            0: { color: '#80B2FF' },
            1: { color: '#FF80EB' },
            2: { color: '#FFCC80' },
            3: { color: '#FF808F' },
            4: { color: '#80FF94' },
            5: { color: '#FFD700' }
        },
        tooltip: {
            text: 'percentage'
        },
        pieSliceText: 'none'
    };

    return (
        <div style={{ display: 'flex', maxWidth: 900, margin: 'auto', justifyContent: 'center' }}>
            <div className="chart-container">
                <Chart
                    chartType="PieChart"
                    data={data}
                    options={options}
                    width="500px"
                    height="500px"
                    legendToggle
                />
               <div style={{ marginTop: '20px' }}>
               {sortedPercentages.map((item, index) => (
                    <div key={index} style={{ marginBottom: '5px' }}>
                        <span style={{ color: options.slices[index].color, fontWeight: 'bold' }}>{item.name}:</span> {item.percentage}%
                    </div>
                ))}
            </div>
            </div>
            <br/>
            <div>가장 지출 많은 카테고리 :  {highestCategory.name}</div>
        </div>
    );
};

export default MyChart;

소비패턴 분석 그래프

import React from 'react';
import { Chart } from "react-google-charts";
import './WeeklyChart.css';

const data = [
  ["요일", "소비 금액", { role: "style" }, { role: "annotation" }],
  ["Sat", 10000, "#EDF0F7", "10000원"],
  ["Sun", 8000, "#EDF0F7", "8000원"],
  ["Mon", 20000, "#EDF0F7", "20000원"],
  ["Tue", 12000, "#EDF0F7", "12000원"],
  ["Wed", 10000, "#EDF0F7", "10000원"],
  ["Thu", 9000, "#EDF0F7", "9000원"],
  ["Fri", 13000, "#EDF0F7", "13000원"]
];

// 가장 높은 값을 찾아 색상 변경
const maxIndex = data.reduce((maxIdx, row, idx, arr) => row[1] > arr[maxIdx][1] ? idx : maxIdx, 1);
data[maxIndex][2] = "#476EFF";

// 총 소비 금액 계산
const totalSpending = data.slice(1).reduce((acc, row) => acc + row[1], 0);

const options = {
  title: "주간 소비 리포트",
  hAxis: { 
    gridlines: { color: 'transparent' },
    baselineColor: 'transparent'
  },
  vAxis: { 
    gridlines: { color: 'transparent' },
    baselineColor: 'transparent',
    textPosition: 'none'
  },
  legend: "none",
  bar: { groupWidth: "80%" }, // 막대의 폭 조정
  isStacked: true,
  animation: {
    startup: true,
    easing: 'inAndOut',
    duration: 1000,
  },
//   막대 그래프 크기
  chartArea: {
    width: '90%',
    height: '70%'
  },
  annotations: {
    alwaysOutside: true,
    textStyle: {
      fontSize: 14,
      auraColor: 'none',
      color: '#000'
    },
    stem: {
      color: 'transparent'
    }
  }
};

const WeeklyChart = () => {
  return (
    <div className="chart-container">
      <Chart
        chartType="ColumnChart"
        width="500px"  // 차트의 가로 크기 설정
        height="500px" // 차트의 세로 크기 설정
        data={data}
        options={options}
        loader={<div>Loading Chart...</div>}
      />
      <div>주간 총 소비 금액: {totalSpending.toLocaleString()}원</div>  
    </div>
  );
};

export default WeeklyChart;

주간 소비 리포트

반응형