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

195 Posts

Post

Replies

Boosts

Views

Activity

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.8k
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
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.8k
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
1.9k
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.1k
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
2k
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
Sub-second X AxisMarks in SwiftUI Charts time series line chart
I already have a working app, using SwiftUI Canvas, for charting sensor milliVolt data at a frequency of 130Hz, so thought I'd see how SwiftUI Charts compared for ease of implementation. Charts is much easier to implement, saving the tedium of scaling and label context placement. However, creating the AxisMarks.Values was a problem because the stride-by method with Calendar.Component has .second as the smallest unit, and I need deciSecond. I tried some other inbuillt options, e.g. desiredCount, but no joy. After a while I realised that I can create my own values array using a function, so here it is (hoping that this helps someone, somewhere, sometime): struct ChartView: View {     var chartData : [DataPoint] // An array of CoreData objects with timeStamp and milliVolt attributes let xSecStyle = StrokeStyle(lineWidth: 1.0)     let xDeciSecStyle = StrokeStyle(lineWidth: 0.5) ... // The .chartAxis code within Chart in body .chartXAxis {                 AxisMarks(values: deciSecValues) { value in                     if Double(value.index).remainder(dividingBy: 10.0)  == 0.0 { // show the second-gridline as wider and display the time label                         AxisGridLine(stroke:xSecStyle)                                 .foregroundStyle(.orange)                         AxisValueLabel(format: .dateTime.minute().second(),centered: false)                     } else {                         AxisGridLine(stroke:xDeciSecStyle)                                 .foregroundStyle(.orange)                     }                 }             } ..... // The func for creating the X Axis Marks private var deciSecValues : [Date] {         var xDates = [Date]()         if chartData.isEmpty { return xDates }         let deciSecs = (Int(chartData.last!.timeStamp!.timeIntervalSince(chartData.first!.timeStamp!)) + 1) * 10         for i in stride(from: 0, to: deciSecs, by: 1) {             let newTime = Double(i) / 10.0             xDates.append(chartData.first!.timeStamp!.addingTimeInterval(newTime))         }         return xDates     } Regards, Michaela
0
1
1.7k
Jul ’22
SwiftUI Chart scale issue
Hey guys I'm playing around with swiftUI charts using data from Yahoo Finance public api. I'm getting a data set of charts data and trying to display it using SwiftUI charts. My chart seems broken compared to what I'm seeing on the Yahoo webpage: My code looks like this (tried to keep it super simple for the example):     VStack {       Chart {         ForEach(viewmodel.chartData1) { chartData in           LineMark(x: .value("date", chartData.date),                y: .value("amount", "\(chartData.high)"))           .interpolationMethod(.catmullRom)                                 }       }     }     .task { await viewmodel.getSymbols() }   } So I'm not sure what I'm doing wrong and why does my chart looks downward trending like that. Any help, any lead would help!
1
0
1.9k
Jul ’22
Value based colors
How to create a chart where each data mark has a color based on its value? Like this chart: https://observablehq.com/@d3/gradient-encoding With the following code, the whole curve has one color only. My function Color.forTemperature() returns different colors for different temperatures. Chart(temperatures) { temperature in LineMark(     x: .value("Day", temperature.date, unit: .day),         y: .value("Temperature", temperature.value)     ) .foregroundStyle(Color.forTemperature(temperature.value)) }
2
0
1.7k
Jul ’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.8k
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
How to make linemark stretch to end of x-axis with dates
Hi there, as you can see from the picture I have dates on x-axis in the format "MM-yyyy", I want the line and areamark to stretch to the end of the graph. You got any suggestions? thanks in advance :)
Replies
1
Boosts
0
Views
1.1k
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
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.8k
Activity
Aug ’22
Little question
Is it possible to have a custom symbol just at the head of the line chart? EX: Live line chart where the head is a little circle
Replies
0
Boosts
0
Views
1k
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
1.9k
Activity
Aug ’22
can i use Swift Charts with ios 15?
i can't find a solution to install this, so i thought that maybe i have to have xcode 14 and sdk set to 16, can someone give me a solution for using this library please?
Replies
1
Boosts
0
Views
1.1k
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.1k
Activity
Jul ’22
Will Swift Charts be available on iOS 15?
Would love to use Swift Charts framework. But I still need to support older iOS versions. Do I need create custom chart solution for iOS15 or any chance SwiftCharts will be backward compatible?
Replies
2
Boosts
4
Views
3.7k
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
2k
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
Sub-second X AxisMarks in SwiftUI Charts time series line chart
I already have a working app, using SwiftUI Canvas, for charting sensor milliVolt data at a frequency of 130Hz, so thought I'd see how SwiftUI Charts compared for ease of implementation. Charts is much easier to implement, saving the tedium of scaling and label context placement. However, creating the AxisMarks.Values was a problem because the stride-by method with Calendar.Component has .second as the smallest unit, and I need deciSecond. I tried some other inbuillt options, e.g. desiredCount, but no joy. After a while I realised that I can create my own values array using a function, so here it is (hoping that this helps someone, somewhere, sometime): struct ChartView: View {     var chartData : [DataPoint] // An array of CoreData objects with timeStamp and milliVolt attributes let xSecStyle = StrokeStyle(lineWidth: 1.0)     let xDeciSecStyle = StrokeStyle(lineWidth: 0.5) ... // The .chartAxis code within Chart in body .chartXAxis {                 AxisMarks(values: deciSecValues) { value in                     if Double(value.index).remainder(dividingBy: 10.0)  == 0.0 { // show the second-gridline as wider and display the time label                         AxisGridLine(stroke:xSecStyle)                                 .foregroundStyle(.orange)                         AxisValueLabel(format: .dateTime.minute().second(),centered: false)                     } else {                         AxisGridLine(stroke:xDeciSecStyle)                                 .foregroundStyle(.orange)                     }                 }             } ..... // The func for creating the X Axis Marks private var deciSecValues : [Date] {         var xDates = [Date]()         if chartData.isEmpty { return xDates }         let deciSecs = (Int(chartData.last!.timeStamp!.timeIntervalSince(chartData.first!.timeStamp!)) + 1) * 10         for i in stride(from: 0, to: deciSecs, by: 1) {             let newTime = Double(i) / 10.0             xDates.append(chartData.first!.timeStamp!.addingTimeInterval(newTime))         }         return xDates     } Regards, Michaela
Replies
0
Boosts
1
Views
1.7k
Activity
Jul ’22
SwiftUI Chart scale issue
Hey guys I'm playing around with swiftUI charts using data from Yahoo Finance public api. I'm getting a data set of charts data and trying to display it using SwiftUI charts. My chart seems broken compared to what I'm seeing on the Yahoo webpage: My code looks like this (tried to keep it super simple for the example):     VStack {       Chart {         ForEach(viewmodel.chartData1) { chartData in           LineMark(x: .value("date", chartData.date),                y: .value("amount", "\(chartData.high)"))           .interpolationMethod(.catmullRom)                                 }       }     }     .task { await viewmodel.getSymbols() }   } So I'm not sure what I'm doing wrong and why does my chart looks downward trending like that. Any help, any lead would help!
Replies
1
Boosts
0
Views
1.9k
Activity
Jul ’22
Value based colors
How to create a chart where each data mark has a color based on its value? Like this chart: https://observablehq.com/@d3/gradient-encoding With the following code, the whole curve has one color only. My function Color.forTemperature() returns different colors for different temperatures. Chart(temperatures) { temperature in LineMark(     x: .value("Day", temperature.date, unit: .day),         y: .value("Temperature", temperature.value)     ) .foregroundStyle(Color.forTemperature(temperature.value)) }
Replies
2
Boosts
0
Views
1.7k
Activity
Jul ’22