Charts 기본 라이브러리 사용하기

버질·2024년 12월 11일

1. SwiftUI Charts 라이브러리 소개

지원 환경: iOS 16 이상, macOS 13 이상

사용 목적: SwiftUI 기반으로 간단하고 직관적인 방식으로 차트를 생성 및 관리.

지원되는 Chart Markers:
BarMark, LineMark, PointMark, AreaMark 등 다양한 마크를 통해 차트를 표현

기본 흐름:
데이터 타입 정의
Chart 뷰에 데이터를 전달
데이터에 맞는 Mark를 사용하여 차트를 구성

2. 기본 바 차트 생성

목표: 각 장난감 유형(Cube, Sphere, Pyramid)에 대한 개수를 보여주는 바 차트를 생성.
코드:

import SwiftUI
import Charts

struct ToyShape: Identifiable {
    var type: String
    var count: Double
    var id = UUID()
}

struct ContentView: View {
    var data: [ToyShape] = [
        .init(type: "Cube", count: 5),
        .init(type: "Sphere", count: 4),
        .init(type: "Pyramid", count: 4)
    ]

    var body: some View {
        Chart {
            ForEach(data) { shape in
                BarMark(
                    x: .value("Shape Type", shape.type),
                    y: .value("Total Count", shape.count)
                )
                .foregroundStyle(.red) // 바 색상 설정
            }
        }
    }
}

결과: 각 장난감 유형별 개수를 빨간색 바 차트로 표시.

3. 데이터별로 색상을 지정

목표: 각 바에 대해 서로 다른 색상을 적용.
코드:

import SwiftUI
import Charts

struct ToyShape: Identifiable {
    var type: String
    var count: Double
    var id = UUID()
    var color: Color
}

struct ContentView: View {
    var data: [ToyShape] = [
        .init(type: "Cube", count: 5, color: .red),
        .init(type: "Sphere", count: 4, color: .blue),
        .init(type: "Pyramid", count: 4, color: .yellow)
    ]

    var body: some View {
        Chart {
            ForEach(data) { shape in
                BarMark(
                    x: .value("Shape Type", shape.type),
                    y: .value("Total Count", shape.count)
                )
                .foregroundStyle(shape.color) // 데이터별 색상 적용
            }
        }
    }
}

결과: 각 장난감 유형별로 정의한 색상(red, blue, yellow)이 적용된 바 차트 생성.

4. Plottable 프로토콜 활용

목표: 데이터 타입을 정리하고, Plottable 프로토콜을 사용해 X축 데이터를 커스텀 타입으로 설정.
코드:

import SwiftUI
import Charts

enum ToyType: String, Plottable {
    case cube = "Cube"
    case sphere = "Sphere"
    case pyramid = "Pyramid"
}

struct ToyShape: Identifiable {
    var color: String
    var type: ToyType
    var count: Double
    var id = UUID()
}

struct ContentView: View {
    var stackedBarData: [ToyShape] = [
        .init(color: "Green", type: .cube, count: 2),
        .init(color: "Green", type: .sphere, count: 0),
        .init(color: "Green", type: .pyramid, count: 1),
        .init(color: "Purple", type: .cube, count: 1),
        .init(color: "Purple", type: .sphere, count: 1),
        .init(color: "Purple", type: .pyramid, count: 1),
        .init(color: "Pink", type: .cube, count: 1),
        .init(color: "Pink", type: .sphere, count: 2),
        .init(color: "Pink", type: .pyramid, count: 0),
        .init(color: "Yellow", type: .cube, count: 1),
        .init(color: "Yellow", type: .sphere, count: 1),
        .init(color: "Yellow", type: .pyramid, count: 2)
    ]

    var body: some View {
        Chart {
            ForEach(stackedBarData) { shape in
                BarMark(
                    x: .value("Shape Type", shape.type),
                    y: .value("Total Count", shape.count)
                )
                .foregroundStyle(by: .value("Shape Color", shape.color)) // 색상 그룹화
            }
        }
        .chartForegroundStyleScale([
            "Green": .green, "Purple": .purple, "Pink": .pink, "Yellow": .yellow
        ])
    }
}

결과:
X축은 ToyType으로 구분.
각 바의 색상은 Shape Color 기준으로 설정.

5. 학습한 점

Chart 구조 이해:
Chart 내부에 Mark(예: BarMark)를 사용해 차트를 구성.
데이터와 스타일 설정:
PlottableValue와 Plottable을 활용해 데이터를 커스터마이징.
.foregroundStyle과 .chartForegroundStyleScale로 차트 스타일을 유연하게 설정.
실제 활용성:
iOS/macOS에서 데이터 시각화 기능을 빠르고 간단하게 구현 가능.
다양한 차트 유형과 속성 지원.

6. 다음 단계

LineMark, PointMark 등을 활용한 다양한 차트 실습.
동적 데이터와 연동해 실시간 차트 생성 테스트.
사용자 상호작용(예: 드래그, 확대) 기능 구현 탐구.

profile
iOS Developer · SwiftUI & UIKit '가끔 되고 가끔 안 되는' 문제를 뿌리부터 잡습니다.

0개의 댓글