Swift Charts

RSS for tag

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

Posts under Swift Charts tag

198 Posts

Post

Replies

Boosts

Views

Activity

Charts module not available in Xcode 14.0.1 for macOS app
During the upgrade to Ventura it appears that Xcode was also upgraded to 14.0.1. In an attempt to use a new feature, Charts, I entered into a macOS app import Charts and I get an error message no such module Charts. If I use the same import Charts in an iOS app I do not get such an error. I am wondering if Charts in not available for macOS apps or did something go wrong during the Ventura upgrade. If it is the later, it makes sense to me to cleanly uninstall Xcode and reinstall. But it is unclear if just dragging Xcode from the application folder to the trash and emptying the trash completely uninstalls Xcode. As a side note, I do not ever remember Xcode being upgraded during an upgrade to macOS. Any input will be appreciated.
1
1
1.9k
Oct ’22
How can I include a function (or calculation) in the values that Charts receives to draw the chart, and overcome this bug?
Charts fails when a function or ternary condition is added to the values to be plotted. Charts. When a function is received as a value in the ForEach loop, the application crashes (Thread 1: signal SIGABRT), or if it is a ternary operator (condition ? true: false) it does not show the graph. The function should convert the value/attribute of the Core Data entity only if necessary, the data is stored in a common unit and depending on the display condition in an AppStorage variable it should be seen converted to another unit or displayed. This error occurs with any type of chart. It fails with both RulerMark and other charts like LineMark. The function works fine with Text and other similar views. The Chart @AppStorage("unitView") var unitView: String = "Celsius" ... // CHART Chart { if statsByUser.takens > 1 { RuleMark(y: .value("AVG", getViewDegrees(statsByUser.avg, unitView))) .lineStyle(StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round, dash: [4, 6])) .foregroundStyle(.white.opacity(0.8)) } ForEach(0..<temperatureByUserId.count, id:\.self) { item in LineMark(x: .value("Date", item + 1), y: .value("Temperature", getViewDegrees(temperatureByUserId[item].degress, unitView))) .lineStyle(.init(lineWidth: 2, lineCap: .round, lineJoin: .round)) .foregroundStyle(.white) //.mint [.pink, .purple, .mint] } .interpolationMethod(.cardinal) } // X-Axis .chartXScale(domain: 1 ... statsByUser.takens) .chartXAxis(.hidden) // Y-Axis .chartYScale(domain: statsByUser.min ... statsByUser.max) .chartYAxis { AxisMarks{ _ in AxisGridLine().foregroundStyle(.white) AxisValueLabel(centered: true).foregroundStyle(.white) } } } The Functions let unitDegress: [String] = ["Celsius", "Fahrenheit"] func getViewDegrees(_ value: Double, _ unit: String) -> Double { var returnValue = value if unit == unitDegress[1] { // is Fahrenheit let t = Measurement(value: value, unit: UnitTemperature.celsius) returnValue = t.converted(to: .fahrenheit).value } return returnValue } Text works properly. Text("\(getViewDegrees(temperatureByUser.last, unitView), specifier: decimalSpecifier)")
2
0
1.1k
Oct ’22
Interactive Charts
I’ve spent a couple hours trying to figure out how to make SwiftUI charts interactive (not static, can tap, drag, there’s a tooltip and a cursor on the selected data). I found the word “interactive” mentioned even in Apple docs, but not a single handler or any example showing any form of interaction. Every article I found tells me to use a 3rd party package. Is it possible that SwiftUI charts are just static (why would you even have something like that in 2022)? And if so, how did they create the charts in the Health App?
1
0
5.1k
Oct ’22
How to create bar chart with two or more bars per time period
Environment: Xcode 14.1 beta 3 on macOS Ventura Beta 9. No longer need this, I found example of this. struct LocationsChart: View {     var body: some View {         Chart {             ForEach(seriesData, id: \.city) { series in                 ForEach(series.data, id: \.weekday) {                     BarMark(                         x: .value("Weekday", $0.weekday, unit: .day),                         y: .value("Sales", $0.sales)                     )                 }                 .foregroundStyle(by: .value("City", series.city))                 .position(by: .value("City", series.city))             }         }     }     let seriesData = [         (             city: "Cupertino", data: [                 (weekday: date(year: 2022, month: 5, day: 2), sales: 54),                 (weekday: date(year: 2022, month: 5, day: 3), sales: 42),                 (weekday: date(year: 2022, month: 5, day: 4), sales: 88),                 (weekday: date(year: 2022, month: 5, day: 5), sales: 49),                 (weekday: date(year: 2022, month: 5, day: 6), sales: 42),                 (weekday: date(year: 2022, month: 5, day: 7), sales: 125),                 (weekday: date(year: 2022, month: 5, day: 8), sales: 67)             ]         ),         (             city: "San Francisco", data: [                 (weekday: date(year: 2022, month: 5, day: 2), sales: 81),                 (weekday: date(year: 2022, month: 5, day: 3), sales: 90),                 (weekday: date(year: 2022, month: 5, day: 4), sales: 52),                 (weekday: date(year: 2022, month: 5, day: 5), sales: 72),                 (weekday: date(year: 2022, month: 5, day: 6), sales: 84),                 (weekday: date(year: 2022, month: 5, day: 7), sales: 84),                 (weekday: date(year: 2022, month: 5, day: 8), sales: 137)             ]         )     ] } func date(year: Int, month: Int, day: Int = 1) -> Date {     Calendar.current.date(from: DateComponents(year: year, month: month, day: day)) ?? Date() }
0
0
1.2k
Oct ’22
foregroundStyle(by: does not maintain consistent colour with limited series
When using foregroundStyle(by: and symbol(by: with a series of data using Multi-series Line Mark and limited with a pickerView, the colour/symbol changes depending on the number of series selected and is not consistent. enum Hand {     case left, right, both } struct HandSample: Identifiable {     var hand: String    // Series     var count: Double     var date: Date     var id = UUID() }     var data: [HandSample] {         switch hand {         case .both:             return loadData(samples: samples, days: days, left: true, right: true)         case .left:             return loadData(samples: samples, days: days, left: true, right: false)         case .right:             return loadData(samples: samples, days: days, left: false, right: true)         }     }     func loadData(samples: FetchedResults<Sample>, days: Int, left: Bool, right: Bool) -> [HandSample] {         var series: Array<HandSample> = Array()         let sinceDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())         for sample in samples {             if sample.sampleDate > sinceDate! {                 if left {                     let leftSamples = HandSample(hand: "Left", count: sample.left.doubleValue, date: sample.sampleDate)                     series.append(leftSamples)                 }                 if right {                     let rightSamples = HandSample(hand: "Right", count: sample.right.doubleValue, date: sample.sampleDate)                     series.append(rightSamples)                 }             }         }         return series     }     var body: some View {         VStack {             Picker ("Hand", selection: $hand.animation(.easeOut)) {                 Text("Both Hands")                     .tag(Hand.both)                 Text("Left Hand")                     .tag(Hand.left)                 Text("Right Hand")                     .tag(Hand.right)             }             .pickerStyle(.segmented)             Chart (data) {                 LineMark(                     x: .value("Date", $0.date),                     y: .value("Count", $0.count),                     series: .value("Hand", $0.hand)                 )                 .foregroundStyle(by: $0.hand)                 PointMark(                     x: .value("Date", $0.date),                     y: .value("Count", $0.count)                 )                 .foregroundStyle(by: $0.hand)                 .symbol(by: .value("Hand", $0.hand))             }         }     } In the attached sample, shows Right as a Green Cross when Both Hands series are shown, but shows Right as a Blue Circle when only the Right Hand series is shown. iOS 16 Beta 4 (20A5328h) Xcode 14.0 beta 4 (14A5284g)
6
0
1.9k
Sep ’22
How to group by the elements of an array in SwiftUI
I have JSON data that I decoded and stored in core data that I am using to populate a SwiftUi line chart. I need to calculate the average of the data by dates. So the average of polling data by months. Sample JSON Data: "president": "Joe Biden", "subgroup": "All polls", "modeldate": "9/9/2022", "startdate": "1/19/2021", "enddate": "1/21/2021", "pollster": "Rasmussen Reports/Pulse Opinion Research", "grade": "B", "samplesize": 1500, "population": "lv", "weight": 0.33818752, "influence": 0, "approve": 48, "disapprove": 45, "adjusted_approve": 49.154266, "adjusted_disapprove": 40.2849, "multiversions": "", "tracking": "T", "url": "https://www.rasmussenreports.com/public_content/politics/biden_administration/biden_approval_index_history", "poll_id": 74247, "question_id": 139395, "createddate": "January 2021", "timestamp": "09:48:31 9 Sep 2022" Data Model: struct PresApprovalDTO: Hashable, Decodable { var president: String var subgroup: String var startdate: String var enddate: String var pollster: String var approve: Double var disapprove: Double var url: String var createddate: String var startDateConverter: Date { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "MM-dd-yyyy" let date = dateFormatter.date(from:startdate) ?? Date() let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day, .hour], from: date) let finalDate = calendar.date(from:components) ?? Date() return(finalDate) } var endDateConverter: Date { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "MM-dd-yyyy" let date = dateFormatter.date(from:enddate) ?? Date() let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day, .hour], from: date) let finalDate = calendar.date(from:components) ?? Date() return(finalDate) } } Chart View Model: import SwiftUI import Charts struct PresApprChart: View { @StateObject private var pollListVM = PollsListViewModel() var body: some View { Chart(pollListVM.presPolls, id: \.url) { item in LineMark(x: .value("Month", item.endDateConverter, unit: .month), y: .value("Approval", item.approve) ) }.frame(width: 325, height: 200) .onAppear(perform: { pollListVM.getAllPresPolls() }) } } struct PresApprChart_Previews: PreviewProvider { static var previews: some View { PresApprChart() } } Above is the result. There are tons of data points for each month, so I need to average them. I tried to map and divide the approved values by the date count, but it averages all the approval data points. LineMark(x: .value("Month", item.endDateConverter, unit: .month), y: .value("Approval", pollListVM.presPolls.map(\.approve).reduce(0.0, +) / Double(item.endDateConverter.asFormattedString().count)) )
0
0
1.5k
Sep ’22
Possible to exclude irrelevant data from axis?
I'm experimenting with replacing my graph implementation with SwiftCharts. One issue I ran into is that I'm graphing stock data, but that data is only present during trading hours. In the screenshot I included, you can see my implementation on top vs the SwiftCharts version as well as the stocks app. Because trading is from 9:30AM-4:00PM, if the times are graphed linearly, there will be large gaps for nights and weekends. The way I implemented this before was to treat each "tick" of data as equal width. .chartXScale(type: .category) seems like it would do something similar, but if I try that I get the following error: Fatal error: the specified scale type is incompatible with the data values and visual property.
1
1
1.1k
Aug ’22
SwiftUI Charts iPhone Crash: Symbol not found (iPhone public Beta 2)
When trying to add modifiers to a chart axis using this code .chartYAxis(content: {               }) the app shows no problem running on the simulator and was working fine when running on iOS16 public beta 1, but is now crashing on iOS16 public beta 2. Here's the whole crash data: _Symbol not found: _$s6Charts16EmptyAxisContentVAA0cD0AAWP  Referenced from: /private/var/containers/Bundle/Application/8F31A53B-BC55-46B5-9304-A30F816BDA2A/PadelCharts.app/PadelCharts  Expected in:    /System/Library/Frameworks/Charts.framework/Charts Symbol not found: $s6Charts16EmptyAxisContentVAA0cD0AAWP  Referenced from: /private/var/containers/Bundle/Application/8F31A53B-BC55-46B5-9304-A30F816BDA2A/PadelCharts.app/PadelCharts  Expected in:    /System/Library/Frameworks/Charts.framework/Charts dyld config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/usr/lib/libBacktraceRecording.dylib:/usr/lib/libMainThreadChecker.dylib:/usr/lib/libRPAC.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
6
2
2.5k
Aug ’22
Plotting a Stock Chart with ScaleType <missing> WeekDay
I'm wondering if Apple will add a weekDay type ScaleType for plotting stock market charts. The Date scaleType assumes that the weekend days (Saturday/Sunday) should be within the plotted data. But the typical stock market chart omits the weekends and holidays (non-market days) from the charts. Would Apple be interested in providing this new Chart Scaling Type. Or is there a way to extend the Charts Framework to allow this type of chart? For Example: the X Axis might look like: M T W T F M T W T F T W T F
1
1
1.9k
Aug ’22
Example in Charts documentation does not work as shown.
Summary: The "ProfitOverTime" example code from https://developer.apple.com/documentation/charts/chart does not compile, and when changes are made to make it compile the chart concatenates the lines rather than having them be separate. Seen in Xcode-Beta's 14.3 and 14. 4 (14A5284g) Is it simply that this method of layering lines is deprecated already? When trying to have a chart with multiple data sets, I copy-pasted the code from the above link and generated the appropriate placeholder data. I got an error that ProfitOverTime was not identifiable, so I added the id on date. In both the case of the years being identical and of the years being different the lines concatenate instead of overlay like in the screenshot on the docs page. Is this method of multiple lines still available and I'm just doing it wrong? Is only method to have multiple lines series as seen on the LineMark docs page? struct ChartTests: View { struct ProfitOverTime { var date: Date var profit: Double } static func months(forYear year:Int) -> [Date] { var days:[Date] = [] var dateComponets = DateComponents() //let year = Calendar.current.component(.year, from: Date()) dateComponets.year = year dateComponets.day = 1 for i in 1...12 { dateComponets.month = i if let date = Calendar.current.date(from: dateComponets) { days.append(date) } } return days } static func dataBuilder(forYear year:Int) -> [ProfitOverTime]{ var data:[ProfitOverTime] = [] for month in months(forYear: year) { let new = ProfitOverTime(date: month, profit: Double.random(in: 200...600)) data.append(new) } return data } let departmentAProfit: [ProfitOverTime] = Self.dataBuilder(forYear: 2021) let departmentBProfit: [ProfitOverTime] = Self.dataBuilder(forYear: 2021) var body: some View { Chart { ForEach(departmentAProfit, id: \.date) { LineMark( x: .value("Date", $0.date), y: .value("Profit A", $0.profit) ) .foregroundStyle(.blue) } ForEach(departmentBProfit, id: \.date) { LineMark( x: .value("Date", $0.date), y: .value("Profit B", $0.profit) ) .foregroundStyle(.green) } RuleMark( y: .value("Threshold", 500.0) ) .foregroundStyle(.red) } } } struct ChartTests_Previews: PreviewProvider { static var previews: some View { ChartTests() } }
5
0
2.0k
Aug ’22
Missing tuple symbols in Charts.
This is Version 13.0 Beta (22A5311f) I see a crash in charts when I try to add more than one item to a Chart.     var body: some View {         Chart {             BarMark(                 x: .value("Shape Type", data[0].type),                 y: .value("Total Count", data[0].count)             )             BarMark(                 x: .value("Shape Type", data[1].type),                 y: .value("Total Count", data[1].count)             )         }     } } This doesn't crash with one item, which isn't a very useful chart. The crash is in the tuple code. Charts17TupleChartContentVMn _  Referenced from: /Users/eoinkortext/Library/Developer/Xcode/DerivedData/Chartest-cviqvlwnwkwzpncsusfuscqjflgt/Build/Products/Debug/Chartest.app/Contents/MacOS/Chartest_ I have logged this in FA already, just posting to see if it is well known, or I am on my own with this.
3
0
1.2k
Jul ’22
Multiple Y axis in single chart?
I have two data sets and I want to show them in the same chart. Both data sets are time based (x axis) and with same time range. They have different units of measure and scaling (y axis). Is it possible to show both data sets in the same chart, but with two different y axis definitions? I have tried to overlay two independent charts but then the two charts are not aligned as I configure one with Y axis to the left and the other with Y axis to the right. Any ideas how to make this happen?
1
0
2.1k
Jul ’22
Scrolling swift Charts and reloading data
Hello! I am trying to do the following: Make a chart that scrolls, but the values ​​of the Y axis do not move, when scrolling, it loads the data / does any action and has dynamic values ​​​​on axis marks (the range should change depending on which marks are currently visible) I understand that I have to handle dots appearing and disappearing as I scroll, but I don't understand where I need to start.
0
4
2.3k
Jul ’22
Swift Chart BarMark Memory Bug and Thread 1: EXC_BAD_ACCES Error
Hello, we've been working with the Swift Chart framework, and the BarMark chart has a memory problem/bug when using it on the iPhone with iOS 16.0 Developer Beta 3. Problem When using the BarMark chart on the simulator with fake values, the chart load, however if we try to load the data on the iPhone, the code breaks with this error: Thread 1: EXC_BAD_ACCESS (code=2, address=0x16d153ff8). This however does not happen when we change the chart type from BarMark to LineMark. Then all of the sudden, the chart loads on the iPhone. Now, when the error hits, Xcode show that the memory usage is extremely high. Working Code High Memory usage and error
1
1
1.2k
Jul ’22
How to show value totals in BarMark Charts
In the WWDC22 video "Design an effective chart", at timestamp 1:22, it shows 4 screenshots with different charts. In the 3rd screenshot from left, it shows the most sold pancake as well as sales of all the different types of pancake. The number of pancakes sold is pinned to the end of each bar, like 278, 247, and so on. How do you show the number like that?
1
0
1.2k
Jul ’22
Charts module not available in Xcode 14.0.1 for macOS app
During the upgrade to Ventura it appears that Xcode was also upgraded to 14.0.1. In an attempt to use a new feature, Charts, I entered into a macOS app import Charts and I get an error message no such module Charts. If I use the same import Charts in an iOS app I do not get such an error. I am wondering if Charts in not available for macOS apps or did something go wrong during the Ventura upgrade. If it is the later, it makes sense to me to cleanly uninstall Xcode and reinstall. But it is unclear if just dragging Xcode from the application folder to the trash and emptying the trash completely uninstalls Xcode. As a side note, I do not ever remember Xcode being upgraded during an upgrade to macOS. Any input will be appreciated.
Replies
1
Boosts
1
Views
1.9k
Activity
Oct ’22
How can I include a function (or calculation) in the values that Charts receives to draw the chart, and overcome this bug?
Charts fails when a function or ternary condition is added to the values to be plotted. Charts. When a function is received as a value in the ForEach loop, the application crashes (Thread 1: signal SIGABRT), or if it is a ternary operator (condition ? true: false) it does not show the graph. The function should convert the value/attribute of the Core Data entity only if necessary, the data is stored in a common unit and depending on the display condition in an AppStorage variable it should be seen converted to another unit or displayed. This error occurs with any type of chart. It fails with both RulerMark and other charts like LineMark. The function works fine with Text and other similar views. The Chart @AppStorage("unitView") var unitView: String = "Celsius" ... // CHART Chart { if statsByUser.takens > 1 { RuleMark(y: .value("AVG", getViewDegrees(statsByUser.avg, unitView))) .lineStyle(StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round, dash: [4, 6])) .foregroundStyle(.white.opacity(0.8)) } ForEach(0..<temperatureByUserId.count, id:\.self) { item in LineMark(x: .value("Date", item + 1), y: .value("Temperature", getViewDegrees(temperatureByUserId[item].degress, unitView))) .lineStyle(.init(lineWidth: 2, lineCap: .round, lineJoin: .round)) .foregroundStyle(.white) //.mint [.pink, .purple, .mint] } .interpolationMethod(.cardinal) } // X-Axis .chartXScale(domain: 1 ... statsByUser.takens) .chartXAxis(.hidden) // Y-Axis .chartYScale(domain: statsByUser.min ... statsByUser.max) .chartYAxis { AxisMarks{ _ in AxisGridLine().foregroundStyle(.white) AxisValueLabel(centered: true).foregroundStyle(.white) } } } The Functions let unitDegress: [String] = ["Celsius", "Fahrenheit"] func getViewDegrees(_ value: Double, _ unit: String) -> Double { var returnValue = value if unit == unitDegress[1] { // is Fahrenheit let t = Measurement(value: value, unit: UnitTemperature.celsius) returnValue = t.converted(to: .fahrenheit).value } return returnValue } Text works properly. Text("\(getViewDegrees(temperatureByUser.last, unitView), specifier: decimalSpecifier)")
Replies
2
Boosts
0
Views
1.1k
Activity
Oct ’22
Interactive Charts
I’ve spent a couple hours trying to figure out how to make SwiftUI charts interactive (not static, can tap, drag, there’s a tooltip and a cursor on the selected data). I found the word “interactive” mentioned even in Apple docs, but not a single handler or any example showing any form of interaction. Every article I found tells me to use a 3rd party package. Is it possible that SwiftUI charts are just static (why would you even have something like that in 2022)? And if so, how did they create the charts in the Health App?
Replies
1
Boosts
0
Views
5.1k
Activity
Oct ’22
Is it possible to have secondary y axis with different scale?
Environment : macOS Ventura Xcode beta 14.1: I have the following chart I was using to learn about SwifUI Charts: I wanted to have different scales on the leading and trailing yaxis as well as have the first 3 bars to use leading scale and the last two bars use the trailing scale. Can this be done? If so, how? Thanks
Replies
1
Boosts
0
Views
1.2k
Activity
Oct ’22
How to create bar chart with two or more bars per time period
Environment: Xcode 14.1 beta 3 on macOS Ventura Beta 9. No longer need this, I found example of this. struct LocationsChart: View {     var body: some View {         Chart {             ForEach(seriesData, id: \.city) { series in                 ForEach(series.data, id: \.weekday) {                     BarMark(                         x: .value("Weekday", $0.weekday, unit: .day),                         y: .value("Sales", $0.sales)                     )                 }                 .foregroundStyle(by: .value("City", series.city))                 .position(by: .value("City", series.city))             }         }     }     let seriesData = [         (             city: "Cupertino", data: [                 (weekday: date(year: 2022, month: 5, day: 2), sales: 54),                 (weekday: date(year: 2022, month: 5, day: 3), sales: 42),                 (weekday: date(year: 2022, month: 5, day: 4), sales: 88),                 (weekday: date(year: 2022, month: 5, day: 5), sales: 49),                 (weekday: date(year: 2022, month: 5, day: 6), sales: 42),                 (weekday: date(year: 2022, month: 5, day: 7), sales: 125),                 (weekday: date(year: 2022, month: 5, day: 8), sales: 67)             ]         ),         (             city: "San Francisco", data: [                 (weekday: date(year: 2022, month: 5, day: 2), sales: 81),                 (weekday: date(year: 2022, month: 5, day: 3), sales: 90),                 (weekday: date(year: 2022, month: 5, day: 4), sales: 52),                 (weekday: date(year: 2022, month: 5, day: 5), sales: 72),                 (weekday: date(year: 2022, month: 5, day: 6), sales: 84),                 (weekday: date(year: 2022, month: 5, day: 7), sales: 84),                 (weekday: date(year: 2022, month: 5, day: 8), sales: 137)             ]         )     ] } func date(year: Int, month: Int, day: Int = 1) -> Date {     Calendar.current.date(from: DateComponents(year: year, month: month, day: day)) ?? Date() }
Replies
0
Boosts
0
Views
1.2k
Activity
Oct ’22
foregroundStyle(by: does not maintain consistent colour with limited series
When using foregroundStyle(by: and symbol(by: with a series of data using Multi-series Line Mark and limited with a pickerView, the colour/symbol changes depending on the number of series selected and is not consistent. enum Hand {     case left, right, both } struct HandSample: Identifiable {     var hand: String    // Series     var count: Double     var date: Date     var id = UUID() }     var data: [HandSample] {         switch hand {         case .both:             return loadData(samples: samples, days: days, left: true, right: true)         case .left:             return loadData(samples: samples, days: days, left: true, right: false)         case .right:             return loadData(samples: samples, days: days, left: false, right: true)         }     }     func loadData(samples: FetchedResults<Sample>, days: Int, left: Bool, right: Bool) -> [HandSample] {         var series: Array<HandSample> = Array()         let sinceDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())         for sample in samples {             if sample.sampleDate > sinceDate! {                 if left {                     let leftSamples = HandSample(hand: "Left", count: sample.left.doubleValue, date: sample.sampleDate)                     series.append(leftSamples)                 }                 if right {                     let rightSamples = HandSample(hand: "Right", count: sample.right.doubleValue, date: sample.sampleDate)                     series.append(rightSamples)                 }             }         }         return series     }     var body: some View {         VStack {             Picker ("Hand", selection: $hand.animation(.easeOut)) {                 Text("Both Hands")                     .tag(Hand.both)                 Text("Left Hand")                     .tag(Hand.left)                 Text("Right Hand")                     .tag(Hand.right)             }             .pickerStyle(.segmented)             Chart (data) {                 LineMark(                     x: .value("Date", $0.date),                     y: .value("Count", $0.count),                     series: .value("Hand", $0.hand)                 )                 .foregroundStyle(by: $0.hand)                 PointMark(                     x: .value("Date", $0.date),                     y: .value("Count", $0.count)                 )                 .foregroundStyle(by: $0.hand)                 .symbol(by: .value("Hand", $0.hand))             }         }     } In the attached sample, shows Right as a Green Cross when Both Hands series are shown, but shows Right as a Blue Circle when only the Right Hand series is shown. iOS 16 Beta 4 (20A5328h) Xcode 14.0 beta 4 (14A5284g)
Replies
6
Boosts
0
Views
1.9k
Activity
Sep ’22
How to group by the elements of an array in SwiftUI
I have JSON data that I decoded and stored in core data that I am using to populate a SwiftUi line chart. I need to calculate the average of the data by dates. So the average of polling data by months. Sample JSON Data: "president": "Joe Biden", "subgroup": "All polls", "modeldate": "9/9/2022", "startdate": "1/19/2021", "enddate": "1/21/2021", "pollster": "Rasmussen Reports/Pulse Opinion Research", "grade": "B", "samplesize": 1500, "population": "lv", "weight": 0.33818752, "influence": 0, "approve": 48, "disapprove": 45, "adjusted_approve": 49.154266, "adjusted_disapprove": 40.2849, "multiversions": "", "tracking": "T", "url": "https://www.rasmussenreports.com/public_content/politics/biden_administration/biden_approval_index_history", "poll_id": 74247, "question_id": 139395, "createddate": "January 2021", "timestamp": "09:48:31 9 Sep 2022" Data Model: struct PresApprovalDTO: Hashable, Decodable { var president: String var subgroup: String var startdate: String var enddate: String var pollster: String var approve: Double var disapprove: Double var url: String var createddate: String var startDateConverter: Date { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "MM-dd-yyyy" let date = dateFormatter.date(from:startdate) ?? Date() let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day, .hour], from: date) let finalDate = calendar.date(from:components) ?? Date() return(finalDate) } var endDateConverter: Date { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "MM-dd-yyyy" let date = dateFormatter.date(from:enddate) ?? Date() let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day, .hour], from: date) let finalDate = calendar.date(from:components) ?? Date() return(finalDate) } } Chart View Model: import SwiftUI import Charts struct PresApprChart: View { @StateObject private var pollListVM = PollsListViewModel() var body: some View { Chart(pollListVM.presPolls, id: \.url) { item in LineMark(x: .value("Month", item.endDateConverter, unit: .month), y: .value("Approval", item.approve) ) }.frame(width: 325, height: 200) .onAppear(perform: { pollListVM.getAllPresPolls() }) } } struct PresApprChart_Previews: PreviewProvider { static var previews: some View { PresApprChart() } } Above is the result. There are tons of data points for each month, so I need to average them. I tried to map and divide the approved values by the date count, but it averages all the approval data points. LineMark(x: .value("Month", item.endDateConverter, unit: .month), y: .value("Approval", pollListVM.presPolls.map(\.approve).reduce(0.0, +) / Double(item.endDateConverter.asFormattedString().count)) )
Replies
0
Boosts
0
Views
1.5k
Activity
Sep ’22
Possible to exclude irrelevant data from axis?
I'm experimenting with replacing my graph implementation with SwiftCharts. One issue I ran into is that I'm graphing stock data, but that data is only present during trading hours. In the screenshot I included, you can see my implementation on top vs the SwiftCharts version as well as the stocks app. Because trading is from 9:30AM-4:00PM, if the times are graphed linearly, there will be large gaps for nights and weekends. The way I implemented this before was to treat each "tick" of data as equal width. .chartXScale(type: .category) seems like it would do something similar, but if I try that I get the following error: Fatal error: the specified scale type is incompatible with the data values and visual property.
Replies
1
Boosts
1
Views
1.1k
Activity
Aug ’22
SwiftUI Charts iPhone Crash: Symbol not found (iPhone public Beta 2)
When trying to add modifiers to a chart axis using this code .chartYAxis(content: {               }) the app shows no problem running on the simulator and was working fine when running on iOS16 public beta 1, but is now crashing on iOS16 public beta 2. Here's the whole crash data: _Symbol not found: _$s6Charts16EmptyAxisContentVAA0cD0AAWP  Referenced from: /private/var/containers/Bundle/Application/8F31A53B-BC55-46B5-9304-A30F816BDA2A/PadelCharts.app/PadelCharts  Expected in:    /System/Library/Frameworks/Charts.framework/Charts Symbol not found: $s6Charts16EmptyAxisContentVAA0cD0AAWP  Referenced from: /private/var/containers/Bundle/Application/8F31A53B-BC55-46B5-9304-A30F816BDA2A/PadelCharts.app/PadelCharts  Expected in:    /System/Library/Frameworks/Charts.framework/Charts dyld config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/usr/lib/libBacktraceRecording.dylib:/usr/lib/libMainThreadChecker.dylib:/usr/lib/libRPAC.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
Replies
6
Boosts
2
Views
2.5k
Activity
Aug ’22
Plotting a Stock Chart with ScaleType <missing> WeekDay
I'm wondering if Apple will add a weekDay type ScaleType for plotting stock market charts. The Date scaleType assumes that the weekend days (Saturday/Sunday) should be within the plotted data. But the typical stock market chart omits the weekends and holidays (non-market days) from the charts. Would Apple be interested in providing this new Chart Scaling Type. Or is there a way to extend the Charts Framework to allow this type of chart? For Example: the X Axis might look like: M T W T F M T W T F T W T F
Replies
1
Boosts
1
Views
1.9k
Activity
Aug ’22
Example in Charts documentation does not work as shown.
Summary: The "ProfitOverTime" example code from https://developer.apple.com/documentation/charts/chart does not compile, and when changes are made to make it compile the chart concatenates the lines rather than having them be separate. Seen in Xcode-Beta's 14.3 and 14. 4 (14A5284g) Is it simply that this method of layering lines is deprecated already? When trying to have a chart with multiple data sets, I copy-pasted the code from the above link and generated the appropriate placeholder data. I got an error that ProfitOverTime was not identifiable, so I added the id on date. In both the case of the years being identical and of the years being different the lines concatenate instead of overlay like in the screenshot on the docs page. Is this method of multiple lines still available and I'm just doing it wrong? Is only method to have multiple lines series as seen on the LineMark docs page? struct ChartTests: View { struct ProfitOverTime { var date: Date var profit: Double } static func months(forYear year:Int) -> [Date] { var days:[Date] = [] var dateComponets = DateComponents() //let year = Calendar.current.component(.year, from: Date()) dateComponets.year = year dateComponets.day = 1 for i in 1...12 { dateComponets.month = i if let date = Calendar.current.date(from: dateComponets) { days.append(date) } } return days } static func dataBuilder(forYear year:Int) -> [ProfitOverTime]{ var data:[ProfitOverTime] = [] for month in months(forYear: year) { let new = ProfitOverTime(date: month, profit: Double.random(in: 200...600)) data.append(new) } return data } let departmentAProfit: [ProfitOverTime] = Self.dataBuilder(forYear: 2021) let departmentBProfit: [ProfitOverTime] = Self.dataBuilder(forYear: 2021) var body: some View { Chart { ForEach(departmentAProfit, id: \.date) { LineMark( x: .value("Date", $0.date), y: .value("Profit A", $0.profit) ) .foregroundStyle(.blue) } ForEach(departmentBProfit, id: \.date) { LineMark( x: .value("Date", $0.date), y: .value("Profit B", $0.profit) ) .foregroundStyle(.green) } RuleMark( y: .value("Threshold", 500.0) ) .foregroundStyle(.red) } } } struct ChartTests_Previews: PreviewProvider { static var previews: some View { ChartTests() } }
Replies
5
Boosts
0
Views
2.0k
Activity
Aug ’22
Missing tuple symbols in Charts.
This is Version 13.0 Beta (22A5311f) I see a crash in charts when I try to add more than one item to a Chart.     var body: some View {         Chart {             BarMark(                 x: .value("Shape Type", data[0].type),                 y: .value("Total Count", data[0].count)             )             BarMark(                 x: .value("Shape Type", data[1].type),                 y: .value("Total Count", data[1].count)             )         }     } } This doesn't crash with one item, which isn't a very useful chart. The crash is in the tuple code. Charts17TupleChartContentVMn _  Referenced from: /Users/eoinkortext/Library/Developer/Xcode/DerivedData/Chartest-cviqvlwnwkwzpncsusfuscqjflgt/Build/Products/Debug/Chartest.app/Contents/MacOS/Chartest_ I have logged this in FA already, just posting to see if it is well known, or I am on my own with this.
Replies
3
Boosts
0
Views
1.2k
Activity
Jul ’22
Multiple Y axis in single chart?
I have two data sets and I want to show them in the same chart. Both data sets are time based (x axis) and with same time range. They have different units of measure and scaling (y axis). Is it possible to show both data sets in the same chart, but with two different y axis definitions? I have tried to overlay two independent charts but then the two charts are not aligned as I configure one with Y axis to the left and the other with Y axis to the right. Any ideas how to make this happen?
Replies
1
Boosts
0
Views
2.1k
Activity
Jul ’22
Scrolling swift Charts and reloading data
Hello! I am trying to do the following: Make a chart that scrolls, but the values ​​of the Y axis do not move, when scrolling, it loads the data / does any action and has dynamic values ​​​​on axis marks (the range should change depending on which marks are currently visible) I understand that I have to handle dots appearing and disappearing as I scroll, but I don't understand where I need to start.
Replies
0
Boosts
4
Views
2.3k
Activity
Jul ’22
Swift Chart BarMark Memory Bug and Thread 1: EXC_BAD_ACCES Error
Hello, we've been working with the Swift Chart framework, and the BarMark chart has a memory problem/bug when using it on the iPhone with iOS 16.0 Developer Beta 3. Problem When using the BarMark chart on the simulator with fake values, the chart load, however if we try to load the data on the iPhone, the code breaks with this error: Thread 1: EXC_BAD_ACCESS (code=2, address=0x16d153ff8). This however does not happen when we change the chart type from BarMark to LineMark. Then all of the sudden, the chart loads on the iPhone. Now, when the error hits, Xcode show that the memory usage is extremely high. Working Code High Memory usage and error
Replies
1
Boosts
1
Views
1.2k
Activity
Jul ’22
How to show value totals in BarMark Charts
In the WWDC22 video "Design an effective chart", at timestamp 1:22, it shows 4 screenshots with different charts. In the 3rd screenshot from left, it shows the most sold pancake as well as sales of all the different types of pancake. The number of pancakes sold is pinned to the end of each bar, like 278, 247, and so on. How do you show the number like that?
Replies
1
Boosts
0
Views
1.2k
Activity
Jul ’22