Swift snippet to create a pie chart using Charts library

October 09, 20241 min read#snippet, #simulator, #swift

This Swift code snippet is a minimal runable code that renders a pie chart using the Charts library.

Code

class PieChartTestVC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupPieChart()
    }

    private func setupPieChart() {
        let pieChartView = PieChartView(frame: self.view.bounds)
        self.view.addSubview(pieChartView)
        
        let entries = [
            PieChartDataEntry(value: 40, label: "Category 1"),
            PieChartDataEntry(value: 30, label: "Category 2"),
            PieChartDataEntry(value: 20, label: "Category 3"),
            PieChartDataEntry(value: 10, label: "Category 4"),
            PieChartDataEntry(value: 15, label: "Category 5"),
            PieChartDataEntry(value: 25, label: "Category 6")
        ]
        
        let dataSet = PieChartDataSet(entries: entries, label: "Funding Fees")
        
        // Set different colors for the categories
        dataSet.colors = [
            UIColor.red,
            UIColor.blue,
            UIColor.green,
            UIColor.yellow,
            UIColor.orange,
            UIColor.purple
        ]
        
        let data = PieChartData(dataSet: dataSet)
        pieChartView.data = data
    }
}

Result

result

Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024