Search code examples
iosswiftios-charts

Charts - ScatterChart 1:1 Axis Scale


I want to plot some x and y data inside a ScatterChartView, but I can't seem to figure out how I can set my x- and y-axis to be scaled equally.

I have tried to use the height and width of the chart to calculate both axes min and max values independently, but that was quite messy and did not lead to any good result.

Do you have any suggestions? Have I overlooked anything inside the documentation?

Underneath is my SwiftUI view I'm using as my scatter plot.

import SwiftUI
import Charts

struct ScatterPlot: UIViewRepresentable {
    typealias UIViewType = ScatterChartView

    private let plot = ScatterChartView()

    func makeUIView(context: Context) -> ScatterChartView {
        setUpPlot()
        return plot
    }

    func updateUIView(_ uiView: ScatterChartView, context: Context) {}

    private func setUpPlot() {
        plot.rightAxis.enabled = false
    
        let dataSets = [getScatterPlotDataSet()]
        let data = ScatterChartData(dataSets: dataSets)
    
        plot.data = data
    }

    private func getScatterPlotDataSet() -> ScatterChartDataSet {
        let entries: [ChartDataEntry] = [ChartDataEntry(x: 0, y: 0), ChartDataEntry(x: 1, y: 1)]
        let dataSet = ScatterChartDataSet(entries: entries)
    
        return dataSet
    }
}

Thanks in advance.


Solution

  • I try to calculate the width and height ratio and get this result

    please note I using storyboard for this example, you need to check are you get correct chart width and height in your swiftUI code

        chart.rightAxis.enabled = false
        
        let width = chart.frame.width
        let height = chart.frame.height
        
        let maxValue: Double = 1.0
        
        chart.xAxis.granularity = 0.5
        chart.leftAxis.granularity = 0.5
        
        chart.leftAxis.axisMaximum = maxValue
        chart.xAxis.axisMinimum = 0
        chart.leftAxis.axisMinimum = 0
        chart.xAxis.axisMaximum = Double(width / height) * maxValue
    

    enter image description here