Swift snippet to create a bar chart using Charts library

October 08, 20242 min read#snippet, #simulator, #swift

This Swift code snippet is a minimal runable code that renders a combined bar and line chart in the same canvas using the Charts library.

Code

class CombinedChartsTestVC: UIViewController {
    
    private lazy var combinedChartView: CombinedChartView = CombinedChartView()
    
    
    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    let unitsSold = [2.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 17.0, 2.0, 4.0, 5.0, 4.0]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(combinedChartView)
        
        combinedChartView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            combinedChartView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            combinedChartView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            combinedChartView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            combinedChartView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            combinedChartView.heightAnchor.constraint(equalToConstant: 200)
        ])

        setChart(xValues: months, yValuesLineChart:  unitsSold, yValuesBarChart: unitsSold)
    }
    
    func setChart(xValues: [String], yValuesLineChart: [Double], yValuesBarChart: [Double]) {
        combinedChartView.noDataText = "Please provide data for the chart."
        
        var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
        var yVals2 : [BarChartDataEntry] = [BarChartDataEntry]()
        
        for i in 0..<xValues.count {
            yVals1.append(ChartDataEntry(x: Double(i), y: yValuesLineChart[i]))
            yVals2.append(BarChartDataEntry(x: Double(i), y: yValuesBarChart[i] - 1))
        }
        
        let lineChartSet = LineChartDataSet(entries: yVals1, label: "Line Data")
        let barChartSet: BarChartDataSet = BarChartDataSet(entries: yVals2, label: "Bar Data")
        
        let data: CombinedChartData = CombinedChartData()
        data.barData = BarChartData(dataSets: [barChartSet])
        data.lineData = LineChartData(dataSets: [lineChartSet])
        
        combinedChartView.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