Swift Charts

RSS for tag

Visualize data with highly customizable charts across all Apple platforms using the compositional syntax of SwifUI.

Swift Charts Documentation

Posts under Swift Charts tag

53 Posts
Sort by:
Post not yet marked as solved
0 Replies
542 Views
I want the line grow without a canvas resize so I need to scale the canvas before the animation. If I apply both X and Y Scale modifiers to set the domain, animation doesn't work, if I comment either of both, yes... Any idea why and any workaround? import SwiftUI import Charts struct Entry: Identifiable { var id = UUID() var time: Double var value: Double } struct ContentView: View { @State var data: [Entry] = [ .init(time: 0, value: 0), .init(time: 1, value: 1)] var body: some View { VStack{ Button("+"){ data.append(.init(time: 2, value: 3)) } Chart(data){entry in LineMark(x: .value("time", entry.time), y: .value("value", entry.value)) } .chartXScale(domain: 0...3) .chartYScale(domain: 0...3) .padding() .animation(.easeIn(duration:3), value: data) } } }
Posted
by
Post not yet marked as solved
3 Replies
1.2k Views
I'm currently in the process on making a horizontally scrollable bar chart with selection. Upon selection, I want to show an annotation attached to a RuleMark. I want to be able to show this annotation above the chart plot area since it is large and will likely cover many bars. I'm using the overflowResolution option on the annotation with the y set to disabled; however, this does not do anything and the annotation seems pushed up inside the plot area rather than overlapping with the plot area itself. If I comment out the chartScrollableAxis modifier than the overflow resolution works as expected.
Posted
by
Post marked as solved
2 Replies
1.2k Views
I have a swift program that displays a chart using Chart. The code includes an X Axis Scale parameter but for some reason the last value (right most) on the x axis does not display. It should display Aug 2023. In checking the array used for the x axis labels I find that the last value is Aug 2023. I do not know how to overcome this obstacle. Any assistance will be appreciated. Below is a picture of the bottom of the chart and the code. struct CustomChartView: View { let vm: SQLDataVM = SQLDataVM.shared let closingValues: [TradingDay] let fundName: String let numYears: Int let maxCloseStruct: TradingDay let maxClose: Double let minCloseStruct: TradingDay let minClose: Double let yIncrment: Double let yAxisValues: [Double] let minTimeStampStruct: TradingDay let minTimeStamp: Date var dateComponent = DateComponents() let maxTimeStampStruct: TradingDay let maxTimeStamp: Date var xAxisValues: [Date] = [] init (fundName: String, numYears: Int) { self.fundName = fundName self.numYears = numYears closingValues = self.vm.QueryDatabase(fundName: fundName, numYears: numYears) maxCloseStruct = self.closingValues.max(by: { (tradingDay1, tradingDay2) -> Bool in return tradingDay1.close < tradingDay2.close })! maxClose = maxCloseStruct.close minCloseStruct = closingValues.min(by: { (tradingDay1, tradingDay2) -> Bool in return tradingDay1.close < tradingDay2.close })! minClose = minCloseStruct.close yIncrment = (maxClose - minClose)/4 yAxisValues = [ minClose, minClose + (1 * yIncrment), minClose + (2 * yIncrment), minClose + (3 * yIncrment), maxClose ] minTimeStampStruct = closingValues.min(by: { (tradingDay1, tradingDay2) -> Bool in return tradingDay1.timeStamp < tradingDay2.timeStamp })! minTimeStamp = minTimeStampStruct.timeStamp maxTimeStampStruct = closingValues.max(by: { (tradingDay1, tradingDay2) -> Bool in return tradingDay1.timeStamp < tradingDay2.timeStamp })! maxTimeStamp = maxTimeStampStruct.timeStamp xAxisValues.append(minTimeStamp) for i in 1...11 { dateComponent.month = i let nextMonth = Calendar.current.date(byAdding: dateComponent, to: minTimeStamp) xAxisValues.append(nextMonth!) } xAxisValues.append(maxTimeStamp) print("\(xAxisValues[12])") // prints 2023-08-04 00:00:00 +0000 } // end init var body: some View { HStack(alignment: .center) { VStack(alignment: .center) { Chart(closingValues, id:\.id) { LineMark( x: .value("Date", $0.timeStamp, unit: .day), y: .value("Closing", $0.close) ) .foregroundStyle(.blue) } // end chart .frame(width: 1000, height: 700, alignment: .center) .chartXAxisLabel(position: .bottom, alignment: .center, spacing: 15) { Text("Date") .font(.custom("Arial", size: 20)) } .chartYAxisLabel(position: .leading, alignment: .center, spacing: 20) { Text("Closing Value") .font(.custom("Arial", size: 20)) } .chartXAxis { AxisMarks(values: xAxisValues) { value in if let date = value.as(Date.self) { AxisValueLabel(horizontalSpacing: -14, verticalSpacing: 10) { VStack(alignment: .leading) { Text(ChartMonthFormatter.string(from: date)) .font(.custom("Arial", size: 14)) Text(ChartYearFormatter.string(from: date)) .font(.custom("Arial", size: 14)) } // end v stack } // end axis label } // end if statement AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1)) .foregroundStyle(Color.black) AxisTick(centered: true, length: 0, stroke: .none) } } // end chart x axis .chartXScale(domain: [xAxisValues[0], xAxisValues[12]]) .chartYAxis { AxisMarks(position: .leading, values: yAxisValues) { value in AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1)) .foregroundStyle(Color.black) AxisTick(centered: true, length: 0, stroke: .none) AxisValueLabel(horizontalSpacing: 10) { if let yAxisValue = value.as(Double.self) { let stringValue = String(format: "$%.02f", yAxisValue) Text(stringValue) .font(.custom("Arial", size: 14)) } } } } .chartYScale(domain: [minClose, maxClose]) .chartPlotStyle { plotArea in plotArea.background(.white.opacity(0.9)) .border(.black, width: 1) } // end chart plot style } // end v stack .frame(width: 1200, height: 900, alignment: .center) } // end h stack } // end some view }
Posted
by
Post not yet marked as solved
2 Replies
736 Views
I'm using .chartAngleSelection to grab the angle of the taps on a SectorMark. When using .chartAngleSelection, it does not register "fast" taps on the screen. You have to hold your finger on the screen for longer than a tap for it to be registered. I've tried the same code with .chartXSelection and .chartYSelection and there is no tap delay. I'm not sure if this is because .chartAngleSelection just came out of beta but it definitely impacts UX.
Posted
by
Post not yet marked as solved
1 Replies
494 Views
I'm currently evaluating Swift Charts to use in my macOS app, where I need to (potentially) display a few millions of data points, ideally all of them at one time. I want to give users the possibility to zoom in & out, so the entire range of values could be displayed at one moment. However, starting at around 20K data points (on my computer), the Chart takes a little bit to set up, but the window resizing is laggy. The performance seems to decrease linearly (?), when dealing with 100K data points you can barely resize the window and the Chart setup/creation is noticeable enough. Dealing with 500K data points is out of the question, the app is pretty much not useable. So I'm wondering if anybody else had a similar issue and what can be done? Is there any "magic" Swift Charts setting that could improve the performance? I have a "data decimation" algorithm, and given no choice I will use it, but somehow I was hoping for Swift Charts to gracefully handle at least 100K data points (there are other libs which do this!). Also, limiting the displayed data range is out of the question for my case, this is a crucial feature of the app. Here's the code that I'm using, but it's the most basic one: struct DataPoint: Identifiable { var id: Double { Double(xValue) } let xValue: Int let yValue: Double } let dataPoints: [DataPoint] = (0..<100_000).map { DataPoint(xValue: $0, yValue: Double($0)) } struct MyChart: View { var body: some View { Chart(dataPoints) { dataPoint in PointMark(x: .value("Index", dataPoint.xValue), y: .value("Y Value", dataPoint.yValue)) } } } Some additional info, if it helps: The Chart is included in a AppKit window via NSHostingController (in my sample project the window contains nothing but the chart) The computer is a MacBook Pro, 2019 and is running macOS 10.14
Posted
by
Post not yet marked as solved
0 Replies
414 Views
Chart { ForEach(viewModel.chartDBdata) { index in LineMark(x: .value("Seq", index.dataSeqInSwing), y: .value("Value",index.value) ) .foregroundStyle(by: .value("itemType", index.itemType)) } } .chartForegroundStyleScale([ "angle": .red, "degree": .orange, "grip1": .yellow, "grip2": .blue ]) .frame(height: 300) .padding() .onAppear{ viewModel.findContact() print("Chart_OnAppear after vm.findcontact") } .tabItem { Image(systemName: "2.circle") Text("data base") }.tag(2) Charts: ScaleResolutionFailure(message: "Scale domain configuration doesn't match encoded value type") <0x10190ebd0> Gesture: System gesture gate timed out. immediately after ForEach looping completion, error message above is shown. why does this happen ?
Posted
by
Post not yet marked as solved
0 Replies
297 Views
Hello, I'm trying to find a way to implement Charts in my project. I'm using storyboard. All the resource that I'm getting everywhere they are using only SwiftUI. Did anyone help me finding a way to implement it.
Posted
by
Post not yet marked as solved
1 Replies
448 Views
I've started using swift charts and since then get random crashes with the error: Thread 467: hit program assert The console outputs the following at the time of the crash: -[MTLDebugRenderCommandEncoder setVertexBufferOffset:atIndex:]:1758: failed assertion Set Vertex Buffer Offset Validation index(0) must have an existing buffer.` I'm not using Metal directly buit it seems like this is related to Swift Charts. I cannot work out the source of the issue from the stack trace and the debugger shows teh crash in libsystem_kernel.dylib so does not tie back to my code. I'm looking for ideas about where to start to try and find the source of the issue 0 libsystem_kernel.dylib 0x9764 __pthread_kill + 8 1 libsystem_pthread.dylib 0x6c28 (Missing UUID 1f30fb9abdf932dba7098417666a7e45) 2 libsystem_c.dylib 0x76ae8 abort + 180 3 libsystem_c.dylib 0x75e44 __assert_rtn + 270 4 Metal 0x1426c4 MTLReportFailure.cold.1 + 46 5 Metal 0x11f22c MTLReportFailure + 464 6 Metal 0x11552c _MTLMessageContextEnd + 876 7 MetalTools 0x95350 -[MTLDebugRenderCommandEncoder setVertexBufferOffset:atIndex:] + 272 8 RenderBox 0xa5e18 RB::RenderQueue::encode(RB::RenderQueue::EncoderState&) + 1804 9 RenderBox 0x7d5fc RB::RenderFrame::encode(RB::RenderFrame::EncoderData&, RB::RenderQueue&) + 432 10 RenderBox 0x7d928 RB::RenderFrame::flush_pass(RB::RenderPass&, bool)::$_4::__invoke(void*) + 48 11 libdispatch.dylib 0x4400 (Missing UUID 9897030f75d3374b8787322d3d72e096) 12 libdispatch.dylib 0xba88 (Missing UUID 9897030f75d3374b8787322d3d72e096) 13 libdispatch.dylib 0xc5f8 (Missing UUID 9897030f75d3374b8787322d3d72e096) 14 libdispatch.dylib 0x17244 (Missing UUID 9897030f75d3374b8787322d3d72e096) 15 libsystem_pthread.dylib 0x3074 (Missing UUID 1f30fb9abdf932dba7098417666a7e45) 16 libsystem_pthread.dylib 0x1d94 (Missing UUID 1f30fb9abdf932dba7098417666a7e45)
Posted
by
Post not yet marked as solved
1 Replies
612 Views
I've been trying to reproduce the example used in the WWDC 23 Presentation "Explore Pit Charts and Interactivity in SwiftCharts" where a popover annotation is set on top of the chart and vertical; RuleMark. However when doing so the annotation doesn't appear at all. I worked around that issue by setting: y: .fit(to: .chart) in the init of the overflowResolution, like: .annotation(position: .top, spacing: 0, overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))) Probably a SwiftUI bug given this API is only a few months old. If anyone has been able to reproduce that example let me know!
Posted
by
Post not yet marked as solved
0 Replies
355 Views
Hello all! I'm implementing a view that shows a grid of different histograms to show a final report to the user. It could have ~100 rows and ~10 columns. I'm using a LazyVGrid and it looks like: Note: the example contains only 3 rows. It takes less than a second to render the grid, but you can feel the app is blocked for a few ms. I was wonder if some of you know how to render asynchronously the chart views so, at least, not block the interface. Thanks!
Posted
by
Post not yet marked as solved
0 Replies
481 Views
I'm seeing an issue related to Swift Charts when I use a @Binding to dynamically change the selection of the chart. Below is a quick example View that demonstrates the issue. This example is a chart that shows a count of events that happened in a day, and the user can touch a bar to reveal the count as an annotation above the bar. The expected behavior is that as the user can touch a bar and see the annotation appear above the bar. In some cases, the chart scale may need to change to allow space for the annotation, which is expected. However, unexpectedly, the whole chart's width changes unexpectedly by a few points, sometimes, when touching a bar. It would be fine if this was consistent with times when the updated scale needs to include an additional digit, however even when that's not the case the whole chart's width seems to change by a few points, and then inconsistently sometimes change back (or not) with subsequent touches. This behavior is not present in all cases, so you may need to run the preview a few times to get data where it's reproducible. Is there something I can do here to fix the issue? Or is it just a bug in Swift Charts? import SwiftUI import Charts struct ContentView: View { var body: some View { VStack { WeekHistogram() .frame(maxHeight: 180) } .padding() } } #Preview { ContentView() } // A simple struct to contain the data for the chart. public struct EventCount: Identifiable { /// Start date of a day let date: Date /// Counts of events on that day public let count: Int /// The ID: date stored as a string public var id: String { date.ISO8601Format() } // Storing a Date as the ID changes how Swift Charts lays them out along the axis to an undesired way. init(day: Date, count: Int) { self.date = day self.count = count } } struct WeekHistogram: View { // Dummy data that gets refreshed every time you run the preview private let countByDay: [EventCount] = EventCount.dummyData // Used to extract the date back from the EventCount.id private let formatter = ISO8601DateFormatter() // The currently selected bar (while user is touching the bar) @State private var selection: String? = nil var body: some View { Chart(countByDay) { element in // X-axis: Date of the event count // Y-axis: Count of events on that date BarMark( x: .value("Day", element.id), y: .value("Count", element.count) ) .annotation(position: .top) { // Only show the annotation when this bar is being touched if element.id == selection { Text("\(element.count)") .font(.headline) } } } .chartXSelection(value: $selection) .chartXAxis { // Custom view to show the weekday and day of the month // Removing this custom .chartXAxis does not fix the issue AxisMarks { value in // Convert the text of the date back to an actual date let date = formatter.date(from: value.as(String.self)!)! AxisValueLabel { VStack { Text(date.formatted(.dateTime.weekday())) Text(date.formatted(.dateTime.day())) .font(.headline) } } } } } } // Generate dummy data extension EventCount { static let dummyData: [EventCount] = { let startOfToday = Calendar.current.startOfDay(for: .now) let secondsPerDay = 24 * 60 * 60 // Generate [EventCount] with a random count from 3–8 for toady and each of the past 7 days. var counts = [EventCount]() for i in 0...7 { let day = startOfToday .addingTimeInterval(TimeInterval(-i * secondsPerDay)) let count = Int.random(in: 3...8) let eventCount = EventCount(day: day, count: count) counts.append(eventCount) } // Reverse the direction to order it for the chart counts.reverse() return counts }() }
Posted
by
Post not yet marked as solved
4 Replies
977 Views
I'm doing a dead simple bar chart. It will show one bar per hour for a few days. The bar chart seems to have a bug where it will overlap the bars as soon as the overall width of the chart reaches some hardcoded value. The chart has .chartScrollableAxes(.horizontal) so horizontal space is no issue, there's infinite amounts of it. This screenshot shows the same content, but the bottom one has 25pt wide bars and the top one 16pt. 16 is the last width before they started overlapping. To test play with numberOfValues as well as the fixed widths for the BarMark:s. Under no circumstances should the bars overlap unless I tell it to, it should use some configurable minimum spacing between bars. In my real case I do not artificially color the bars like this and the chart is really hard to read. I've tried to look in the docs, but most modifiers are totally undocumented and I can't seem to find anything that would apply. By setting .chartXVisibleDomain to some really low value I can force it to spread the bars out more, but then the my bar width is not honoured. import SwiftUI import Charts struct Value: Hashable { let x: Int let y: Int } struct ContentView: View { let values: [Value] let colors: [Color] = [.red, .green, .blue] var body: some View { VStack { Chart { ForEach(values, id: \.self) { value in BarMark( x: .value("X", value.x), y: .value("Y", value.y), width: .fixed(16) ) .foregroundStyle(colors[value.x % colors.count]) } } .chartScrollableAxes(.horizontal) Chart { ForEach(values, id: \.self) { value in BarMark( x: .value("X", value.x), y: .value("Y", value.y), width: .fixed(25) ) .foregroundStyle(colors[value.x % colors.count]) } } .chartScrollableAxes(.horizontal) } .padding() } } #Preview { var rnd = SystemRandomNumberGenerator() let numberOfValues = 50 var values: [Value] = [] for index in 0 ..< numberOfValues { values.append(Value(x: index, y: Int(rnd.next() % 50))) } return ContentView(values: values) } Example with bars the same color. It's pretty much unusable.
Posted
by
Post not yet marked as solved
1 Replies
430 Views
I created a SwiftChart as below and I would like to have two YAxis, one for amount and the second for count. So, the amount YAxis is a different scale then the count YAxis. Does anybody have an example of this or shed some light on coding two different YAxis? Thanks ForEach(seriesArt) { series in ForEach(series.chartSeries.chartEntry) { BarMark( x: .value("Tier", $0.tier), y: .value("Price", $0.keyValue) ) } .foregroundStyle(by: .value("Count", series.chartCategory)) .position(by: .value("Price", series.chartCategory)) } } .frame(width: 400, height: 200) .chartXAxis { AxisMarks(position: .bottom, values: .automatic) { AxisValueLabel() .foregroundStyle(Color.white) } } .chartYAxis { AxisMarks(position: .leading, values: .automatic) { value in AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1)) AxisValueLabel() { if let intValue = value.as(Int.self) { Text("\(intValue)") .font(.system(size: 10)) .foregroundColor(.white) } } } .chartYAixs - for count sum by tier which needs to be a different scale from the amount YAxis } } }
Posted
by
Post not yet marked as solved
0 Replies
518 Views
Hi I am trying to build a pie chart with SwiftUI. I have created one with a dark background, and it seems like labels that correspond to each sector (labels are of black color) are not visible. It would be better to switch these labels' foreground color to white, but I don't see any suitable method to modify this. I tried both chartYAxis and chartXAxis (they worked for BarChart), but the color didn't change. Also, I added a separate struct that conforms to LabelStyle and defines makeBody in the following way struct WhiteLabelStyle : LabelStyle { func makeBody(configuration: Configuration) -> some View { Label { configuration.title.foregroundColor(.white) } icon: { configuration.icon } } } However, that also doesn't change color of labels on a chart. Below the complete code of the view: ZStack { CommonConstants.defaultBackground Chart(data, id: \.name) { name, sales in SectorMark(angle: .value("Value", sales)) .foregroundStyle(by: .value("Product category", name)) } .labelStyle(WhiteLabelStyle()) } Can you suggest any ways to manipulate with a chart comprised of SectorMarks
Posted
by
Post not yet marked as solved
0 Replies
307 Views
Hello, When I input Data 1 into SectorMark and then switch to Data 2, my application crashes. Any suggestions for resolving this issue? Data 1 [ReadingLog.PieChartData(id: "E24A2F4F-5A80-4734-8497-1AE33EF4F007", hour: 4.3, category: "biography"), ReadingLog.PieChartData(id: "710C328D-0B58-4329-A3C1-66CC42A9C602", hour: 0.75, category: "philosophy"), ReadingLog.PieChartData(id: "37F0F9CE-7144-4B78-99C8-921292F6E730", hour: 0.17, category: "novel")] Data 2 [ReadingLog.PieChartData(id: "E24A2F4F-5A80-4734-8497-1AE33EF4F007", hour: 6.3, category: "biography")] Error Message: Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x0000000216287cb8 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [1978] Triggered by Thread: 0 Kernel Triage: VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed
Posted
by
Post not yet marked as solved
1 Replies
377 Views
Hello everyone, I am new to Swift, it is my first project and I am a PhD Electrical Engineer student. I am designing an iOS app for a device that we are designing that is capable of reading electrical brain data and sending them via BLE with a sampling frequency of 2400 Hz. I created a Bluetooth service for the Swift app that every time it receives new data, processes it to split the different channels and add the new data to the Charts data arrays. Here is the code I've designed: func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if characteristic.uuid == Nordic_UART_TX_CHAR_UUID { guard error == nil, let data = characteristic.value else { print("[Bluetooth] Error receiving data or no data: \(error?.localizedDescription ?? "Unknown Error")") return } DispatchQueue.global(qos: .background).async { self.processReceivedData(data) } } } func processReceivedData(_ data: Data) { var batch = [(Int, Int)]() for i in stride(from: 0, to: data.count - 4, by: 4) { let channel = Int(data[i] & 0xFF) let value = Int((Int(data[i + 3] & 0xFF) << 16) | (Int(data[i + 2] & 0xFF) << 8) | (Int(data[i + 1] & 0xFF))) - 8388608 batch.append((channel, value)) } DispatchQueue.main.async { for (channel, value) in batch { let nowTime = (Date().timeIntervalSince1970 - self.dataGraphService.startTime) let newDataPoint = DataGraphService.VoltagePerTime(time: nowTime, voltage: Double(value)/8388608, channel: "Channel \(channel - 15)") if channel == 16 { self.dataGraphService.lastX1 = nowTime self.dataGraphService.dataCh1.append(newDataPoint) } else if channel == 17 { self.dataGraphService.lastX2 = nowTime self.dataGraphService.dataCh2.append(newDataPoint) } else if channel == 18 { self.dataGraphService.lastX3 = nowTime self.dataGraphService.dataCh3.append(newDataPoint) } else if channel == 19 { self.dataGraphService.lastX4 = nowTime self.dataGraphService.dataCh4.append(newDataPoint) } } } } // DataGraphService.swift struct VoltagePerTime { var time: Double var voltage: Double var channel: String } @Published var dataCh1: [VoltagePerTime] = [] @Published var dataCh2: [VoltagePerTime] = [] @Published var dataCh3: [VoltagePerTime] = [] @Published var dataCh4: [VoltagePerTime] = [] @Published var windowSize: Double = 2.0 @Published var lastX1: Double = 0 @Published var lastX2: Double = 0 @Published var lastX3: Double = 0 @Published var lastX4: Double = 0 I also created a View that shows the real-time data from the different channels. ChartView( data: dataGraphService.dataCh1.filter { dataGraphService.getXAxisRange(for: dataGraphService.dataCh1, windowSize: dataGraphService.windowSize).contains($0.time) }, xAxisRange: dataGraphService.getXAxisRange(for: dataGraphService.dataCh1, windowSize: dataGraphService.windowSize), channel: "Channel 1", windowSize: dataGraphService.windowSize ) // ChartView.swift import SwiftUI import Charts struct ChartView: View { var data: [DataGraphService.VoltagePerTime] var xAxisRange: ClosedRange<Double> var channel: String var windowSize: Double var body: some View { RoundedRectangle(cornerRadius: 10) .fill(Color.gray.opacity(0.1)) .overlay( VStack{ Text("\(channel)") .foregroundColor(Color.gray) .font(.system(size: 16, weight: .semibold)) Chart(data, id: \.time) { item in LineMark( x: .value("Time [s]", item.time), y: .value("Voltage [V]", item.voltage) ) } .chartYAxisLabel(position: .leading) { Text("Voltage [V]") } .chartYScale(domain: [-1.6, 1.6]) .chartYAxis { AxisMarks(position: .leading, values: [-1.6, -0.8, 0, 0.8, 1.6]) AxisMarks(values: [-1.6, -1.2, -0.8, -0.4, 0, 0.4, 0.8, 1.2, 1.6]) { AxisGridLine() } } .chartXAxisLabel(position: .bottom, alignment: .center) { Text("Time [s]") } .chartXScale(domain: xAxisRange) .chartXAxis { AxisMarks(values: .automatic(desiredCount: Int(windowSize)*2)) AxisMarks(values: .automatic(desiredCount: 4*Int(windowSize)-2)) { AxisGridLine() } } .padding(5) } ) .padding(2.5) .padding([.leading, .trailing], 5) } } With these code I can receive and plot the data in real-time but after some time the CPU of the iPhone gets saturated and the app stop working. I have the guess that the code is designed in a way that the functions are called one inside the other one in a very fast speed that the CPU cannot handle. My doubt is if there is any other way to code this real-time plotting actions without make the iPhone's CPU power hungry. Thank you very much for your help!
Posted
by
Post not yet marked as solved
0 Replies
299 Views
Hi, I'm making use of iOS17 Charts and getting data from Core Data. Chart { ForEach(weightContext, id: \.timestamp) { series in LineMark( x: .value("Day", series.timestamp!, unit: .day), y: .value("Measurement", WeightFunctions.weightConversions(weightValue: series.value, metric: selectedWeight)) ) PointMark( x: .value("Day", series.timestamp!, unit: .day), y: .value("Measurement", WeightFunctions.weightConversions(weightValue: series.value, metric: selectedWeight)) ) } } .chartYScale(domain: lowestValue...highestValue) .chartScrollableAxes(.horizontal) .chartXVisibleDomain(length: xChartVisible) .chartScrollPosition(x: $xScrollPosition) .chartScrollPosition(initialX: xInitialPosition) // .chartXVisibleDomain(length: xChartVisible) .chartXScale(domain: startDate...endDate) I've linked the .chartXVisibleDomain(length: xChartVisible) to a Picker which changes the length to show month, quarter, half year, year: length = 3600 * 24 * 30, length = 3600 * 24 * 90 etc. Each time the xChartVisible changes the chart sometimes stays in the right area if I'm at the end of the x axis, but otherwise moves out of the view. I've noticed the $xScrollPosition number stays exactly the same, even though the visibility has changed but not sure what to do about that. .onAppear { xInitialPosition = weightPeriodFunc.initialScrollDate xScrollPosition = weightPeriodFunc.initialScrollDate.timeIntervalSinceReferenceDate xChartVisible = weightPeriodFunc.length } .onChange(of: weightPeriod) { newValue in xChartVisible = weightPeriodFunc.length xScrollPosition = newPeriodStartDate.timeIntervalSinceReferenceDate } I've set the xScrollPosition as a TimerInterval as I'm also getting the dates from it's location to provide date information above the chart. @State private var xChartVisible : Int = 3600 * 24 * 90 @State private var xScrollPosition : TimeInterval = TimeInterval() @State private var xInitialPosition : Date = Date() @State private var newPeriodStartDate : Date = Date()
Posted
by