willdale / SwiftUICharts

A charts / plotting library for SwiftUI. Works on macOS, iOS, watchOS, and tvOS and has accessibility features built in.
MIT License
860 stars 108 forks source link

Zoom in to see data points + dynamic labels #94

Closed swelty33 closed 3 years ago

swelty33 commented 3 years ago

I am building a Multi-Line Chart that needs to be able to zoom in and out of based on LARGE number of data points (num data points can be anywhere between 1,000-50,000) and spread over hours of time (x axis). Is there a way to do this currently?

willdale commented 3 years ago

As to the zooming something like:

.frame(width: 300*scale, height: 500)
       .gesture(MagnificationGesture()
              .onChanged({ scale = $0 })
       )

You will need to tweak it to smooth it out.


As to dynamic labels, you could do something like:

.frame(width: 300*scale,
       height: 500)
.gesture(MagnificationGesture()
            .onChanged({
                scale = $0
                if scale > 2 {
                    data.dataSets.dataPoints = zoomedData()
                } else {
                    data.dataSets.dataPoints = normalData()
                }
            })
)
func normalData() -> [LineChartDataPoint] {
    let newDataSet = data.dataSets.dataPoints.indices.map { index -> LineChartDataPoint in
        if index % 2 != 0 {
            var dp = data.dataSets.dataPoints[index]
            dp.xAxisLabel = ""
            return dp
        } else {
            return data.dataSets.dataPoints[index]
        }
    }
    return newDataSet
}

func zoomedData() -> [LineChartDataPoint] {
    [
        LineChartDataPoint(value: 12000, xAxisLabel: "M", description: "Monday"),
        LineChartDataPoint(value: 10000, xAxisLabel: "T", description: "Tuesday"),
        LineChartDataPoint(value: 8000 , xAxisLabel: "W", description: "Wednesday"),
        LineChartDataPoint(value: 17500, xAxisLabel: "T", description: "Thursday"),
        LineChartDataPoint(value: 16000, xAxisLabel: "F", description: "Friday"),
        LineChartDataPoint(value: 11000, xAxisLabel: "S", description: "Saturday"),
        LineChartDataPoint(value: 9000 , xAxisLabel: "S", description: "Sunday"),
    ]
}
swelty33 commented 3 years ago

Thank you very much! Very helpful and tweaking it to work in my env. Appreciate your hard work and for keeping this library online. Cheers

Albinzr commented 2 years ago

Can you give a simple example for this if possible