【Swift】Bar Charts【コピペコード】

2023/06/30に公開

【「ViewController」のコード】

import UIKit
import DGCharts

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createChart()
    }
    
    private func createChart() {
        
        // Create bar chart
        let barChart = BarChartView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width,
                                                  height: view.frame.size.height))
        
        // Configure the axis
        let xAxis = barChart.xAxis
        let rightAxis = barChart.rightAxis
        
        // Configure legend
        let legend = barChart.legend
        
        // Supply data
        var entries = [BarChartDataEntry]()
        var entries2 = [BarChartDataEntry]()
        for x in 0..<10 {
            
            entries.append(
                BarChartDataEntry(
                    x: Double(x),
                    y: Double.random(in: 0...30)
                )
            )
            
            entries2.append(
                BarChartDataEntry(
                    x: Double(x),
                    y: Double.random(in: 0...30)
                )
            )
            
        }
        
        let set = BarChartDataSet(entries: entries, label: "Cost")
        
        // 「colorful」を「joyful」に変えてみる
        // set.colors = ChartColorTemplates.joyful()
        
        set.colors = [
            NSUIColor(cgColor: UIColor.systemBlue.cgColor),
            NSUIColor(cgColor: UIColor.systemPink.cgColor),
            NSUIColor(cgColor: UIColor.systemGreen.cgColor),
            NSUIColor(cgColor: UIColor.systemRed.cgColor),
            NSUIColor(cgColor: UIColor.systemPurple.cgColor),
            NSUIColor(cgColor: UIColor.systemOrange.cgColor),
        ]
        
        
        let set2 = BarChartDataSet(entries: entries2, label: "Cost")
        
        set2.colors = [
            NSUIColor(cgColor: UIColor.systemBlue.cgColor),
            NSUIColor(cgColor: UIColor.systemPink.cgColor),
            NSUIColor(cgColor: UIColor.systemGreen.cgColor),
            NSUIColor(cgColor: UIColor.systemRed.cgColor),
            NSUIColor(cgColor: UIColor.systemPurple.cgColor),
            NSUIColor(cgColor: UIColor.systemOrange.cgColor),
        ]
        
        let data = BarChartData(dataSets: [set,set2])
        
        barChart.data = data
        
        view.addSubview(barChart)
        barChart.center = view.center
    }
    
}

参考動画

Bar Charts in Swift Tutorial (Xcode 12, 2021, Swift 5) - iOS Development
https://www.youtube.com/watch?v=8yPOyh5T2nc&t=20s

Discussion