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

192 Posts

Post

Replies

Boosts

Views

Activity

No playgrounds work "Could not build Objective-C module 'SwiftUI'"
I am unable to run even the simplest of Swift Playgrounds. It's as if the fundamental libraries are missing, but in Xcode I am able to build and run SwiftUI applications. From the main screen under More Playgrounds I click on the App template and before I make any changes it tries to build and fails as per screenshot, with errors such as "Could not build Objective-C module 'SwiftUI'" "Could not build module 'Application Services'" Mac OS 12.6.2 Xcode 14.2 Playgrounds 4.1
3
1
2.4k
Jan ’23
SwiftUI Chart Axis Alignment Issue
I am pretty new to SwiftUII and having trouble understanding how the Plottable value works in SwiftUIChart? I have a simple line chart to show step count. If I define LineMark's x value without unit i.e. value("Week Day", $0.weekday) then plotted data is aligned with x-axis. But, if I define LineMark's x value with unit i.e value("Week Day", $0.weekday, unit: .day) the x-axis does not align with the plotted value’s "date". Meaning that the line get plotted from between the first and second x-axis value.Since the first data from the chart's data array has the date as Jul 17, I was under impression that the line should start from x-axis having value Jul 17, instead is doesn't. If I remove unit then, the line start from Jul 17. struct StepCount: Identifiable {   let id = UUID()   let weekday: Date   let steps: Int   init(day: String, steps: Int) {     let formatter = DateFormatter()     formatter.dateFormat = "yyyyMMdd"     self.weekday = formatter.date(from: day) ?? Date.distantPast     self.steps = steps   } } let currentWeek: [StepCount] = [   StepCount(day: "20220717", steps: 5000),   StepCount(day: "20220718", steps: 15000),   StepCount(day: "20220719", steps: 5000),   StepCount(day: "20220720", steps: 10800),   StepCount(day: "20220721", steps: 5300),   StepCount(day: "20220722", steps: 10400),   StepCount(day: "20220723", steps: 4000) ] struct LineChart: View {   var body: some View {     VStack {       GroupBox ( "Line Chart - Step Count") {         Chart {           ForEach(currentWeek) {             LineMark(               x: .value("Week Day", $0.weekday),               y: .value("Step Count", $0.steps)             )           }         }         .chartYAxis {           AxisMarks(position: .leading)         }         .chartXAxis {           AxisMarks(preset: .aligned, values: .stride(by: .day))         }       }     }   } }
1
2
1.8k
Jan ’23
Charts Framework: chartYScale(domain:) scales the y-axis correctly but BarMarks are drawn down to bottom part of the screen
I'm testing the the new Charts Framework from Apple with Xcode 14.0 Beta 2. But I face some strange issues when I try to scale the y-axis to some concrete values. var body: some View {         VStack {             GroupBox("Serien") {                 Chart {                     ForEach(seriesData) { series in                         BarMark(                             x: .value("Series", series.name),                             y: .value("Wert", series.value)                         )                         .cornerRadius(8.0)                         .annotation(position: .overlay, alignment: .top, spacing: 10.0) {                             Text("\(series.value)")                                 .foregroundColor(.white)                                 .fontWeight(.bold)                         }                     }                     RuleMark(y: .value("Durchschnitt", shotResult.wrappedSeriesAsInt.mean()))                         .foregroundStyle(.red)                 }                 .chartYScale(domain: minSeriesYAxis...maxSeriesYAxis)                 .frame(height: 220, alignment: .topLeading)             }             .backgroundStyle(Color.white)             .shadow(radius: 5.0, x: 2.0, y: 2.0)         }     } Resulting View The LineMark or RectangleMark looks ok. But e.g. the AreaMark has the same issue.
4
3
3.7k
Jan ’23
chartYScale crashes with MTLTExtureDescriptor issue
I'm trying to create a Line Mark with stock data from api. Just using the data will show the chart correctly but I need the Y axis range to not start from 0 but from the minimum value I give it. So I basically call something like this: .chartYScale(domain: viewmodel.range.0...viewmodel.range.1) And these are the range value we are working with: Range (19076.715, 19089.549) doing this basically crash the app with: -[MTLTextureDescriptorInternal validateWithDevice:]:1344: failed assertion `Texture Descriptor Validation MTLTextureDescriptor has height (16811) greater than the maximum allowed size of 8192. what am I doing wrong?
4
2
1.9k
Dec ’22
Charts: If I have one value on my x axis as a date, why is it showing time? Not the date?
Hi Folks, I’m noticing that the charts system I have presents the time of day that something was entered, if it’s a single value. Not the date. So for reference, my chart displays dollar value on the Y axis, and day that value was entered, on the X axis. if I have multiple values entered, it will display the dates. Cool. Although if it’s just one value, it displays the time it was entered, not the date. Which is not great. is there any way to adjust this so it displays the date, regardless of how many values are entered? Thsnks!
0
0
1k
Dec ’22
SwiftUI Scrollable Charts in IOS16
Using the new SwiftUI Charts framework, we can make a chart bigger than the visible screen and place it into a ScrollView to make it scrollable. Something like this: var body : some View { GeometryReader { proxy in ScrollView(.horizontal, showsIndicators: false) { Chart { ForEach(data) { entry in // ... } } .frame(width: proxy.size.width * 2) } } } Does anybody know if it is possible to programmatically move the scroll to display a certain area of the chart? I've tried using ScrollViewReader, setting the IDs at the x-axis labels, and trying to use the scrollTo function to navigate to any of those positions with no luck: Chart { /// ... } .chartXAxis { AxisMarks(values: .stride(by: .day)) { value in if let date : Date = value.as(Date.self) { Text(date, style: .date) .font(.footnote) } } }
1
1
1.9k
Nov ’22
[Swift Charts] custom LineMark symbol is transparent
I have the following Chart and I can't figure out why the AreaMark's are transparent. The area marks are opaque when I move the .symbol view modifier to the AreaMark, but then the gradient doesn't work anymore Any ideas on how to solve this? struct Ranking: Identifiable {     let name: String     let steps: Int     var id: String { name } } let rankings: [Ranking] = [     .init(name: "Tom", steps: 200),     .init(name: "Joseph", steps: 850),     .init(name: "Emil", steps: 700),     .init(name: "Sandra", steps: 100),     .init(name: "Annie", steps: 400),     .init(name: "Teo", steps: 700),     .init(name: "Pär", steps: 400) ] struct ContentView: View {     let curGradient = LinearGradient(         gradient: Gradient (             colors: [                 Color(.blue).opacity(0.1),                 Color(.blue).opacity(0.0)             ]         ),         startPoint: .top,         endPoint: .bottom     )     var body: some View {         VStack() {             Text("Ranking")             Chart {                 ForEach(rankings) { element in                     LineMark(                         x: .value("Name", element.name),                         y: .value("Steps", element.steps)                     )                     .interpolationMethod(.catmullRom)                     .foregroundStyle(.blue)                     .symbol {                         Circle()                             .fill(.white)                             .frame(width: 20)                             .shadow(radius: 2)                     }                     AreaMark(                         x: .value("Name", element.name),                         y: .value("Steps", element.steps)                     )                     .interpolationMethod(.catmullRom)                     .foregroundStyle(curGradient)                 }             }             .chartYAxis(.hidden)             .chartXAxis {                 AxisMarks(position: .top) { value in                     AxisValueLabel(verticalSpacing: 20)                 }             }             .frame(height: 200)             Spacer()         }     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView()     } }
3
0
3.1k
Oct ’22
How do I remove the background lines of a chart
Hello, how do I remove the background lines of a chart and just show the BarMark? import SwiftUI import Charts struct myView: View { var body: some View {  Chart{   BarMark(x: .value("o", 5), y: .value("m", "Duration: 5m"), width: 7) .foregroundStyle(.orange) BarMark(x: .value("o", 7), y: .value("m", "Intervals: 7"), width: 7) .foregroundStyle(.teal)       } } }
3
0
4.1k
Oct ’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.
1
1
1.8k
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
5k
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.8k
Sep ’22
No playgrounds work "Could not build Objective-C module 'SwiftUI'"
I am unable to run even the simplest of Swift Playgrounds. It's as if the fundamental libraries are missing, but in Xcode I am able to build and run SwiftUI applications. From the main screen under More Playgrounds I click on the App template and before I make any changes it tries to build and fails as per screenshot, with errors such as "Could not build Objective-C module 'SwiftUI'" "Could not build module 'Application Services'" Mac OS 12.6.2 Xcode 14.2 Playgrounds 4.1
Replies
3
Boosts
1
Views
2.4k
Activity
Jan ’23
SwiftUI Charts: Is it possible to have a LineChart with a different color line above certain threshold
I have tried different things but I'm not really accomplishing the look I'm going for. Basically what I want is to have a Line Chart that changes color once it reaches certain threshold.
Replies
3
Boosts
0
Views
2.2k
Activity
Jan ’23
SwiftUI Chart Axis Alignment Issue
I am pretty new to SwiftUII and having trouble understanding how the Plottable value works in SwiftUIChart? I have a simple line chart to show step count. If I define LineMark's x value without unit i.e. value("Week Day", $0.weekday) then plotted data is aligned with x-axis. But, if I define LineMark's x value with unit i.e value("Week Day", $0.weekday, unit: .day) the x-axis does not align with the plotted value’s "date". Meaning that the line get plotted from between the first and second x-axis value.Since the first data from the chart's data array has the date as Jul 17, I was under impression that the line should start from x-axis having value Jul 17, instead is doesn't. If I remove unit then, the line start from Jul 17. struct StepCount: Identifiable {   let id = UUID()   let weekday: Date   let steps: Int   init(day: String, steps: Int) {     let formatter = DateFormatter()     formatter.dateFormat = "yyyyMMdd"     self.weekday = formatter.date(from: day) ?? Date.distantPast     self.steps = steps   } } let currentWeek: [StepCount] = [   StepCount(day: "20220717", steps: 5000),   StepCount(day: "20220718", steps: 15000),   StepCount(day: "20220719", steps: 5000),   StepCount(day: "20220720", steps: 10800),   StepCount(day: "20220721", steps: 5300),   StepCount(day: "20220722", steps: 10400),   StepCount(day: "20220723", steps: 4000) ] struct LineChart: View {   var body: some View {     VStack {       GroupBox ( "Line Chart - Step Count") {         Chart {           ForEach(currentWeek) {             LineMark(               x: .value("Week Day", $0.weekday),               y: .value("Step Count", $0.steps)             )           }         }         .chartYAxis {           AxisMarks(position: .leading)         }         .chartXAxis {           AxisMarks(preset: .aligned, values: .stride(by: .day))         }       }     }   } }
Replies
1
Boosts
2
Views
1.8k
Activity
Jan ’23
Charts Framework: chartYScale(domain:) scales the y-axis correctly but BarMarks are drawn down to bottom part of the screen
I'm testing the the new Charts Framework from Apple with Xcode 14.0 Beta 2. But I face some strange issues when I try to scale the y-axis to some concrete values. var body: some View {         VStack {             GroupBox("Serien") {                 Chart {                     ForEach(seriesData) { series in                         BarMark(                             x: .value("Series", series.name),                             y: .value("Wert", series.value)                         )                         .cornerRadius(8.0)                         .annotation(position: .overlay, alignment: .top, spacing: 10.0) {                             Text("\(series.value)")                                 .foregroundColor(.white)                                 .fontWeight(.bold)                         }                     }                     RuleMark(y: .value("Durchschnitt", shotResult.wrappedSeriesAsInt.mean()))                         .foregroundStyle(.red)                 }                 .chartYScale(domain: minSeriesYAxis...maxSeriesYAxis)                 .frame(height: 220, alignment: .topLeading)             }             .backgroundStyle(Color.white)             .shadow(radius: 5.0, x: 2.0, y: 2.0)         }     } Resulting View The LineMark or RectangleMark looks ok. But e.g. the AreaMark has the same issue.
Replies
4
Boosts
3
Views
3.7k
Activity
Jan ’23
chartYScale crashes with MTLTExtureDescriptor issue
I'm trying to create a Line Mark with stock data from api. Just using the data will show the chart correctly but I need the Y axis range to not start from 0 but from the minimum value I give it. So I basically call something like this: .chartYScale(domain: viewmodel.range.0...viewmodel.range.1) And these are the range value we are working with: Range (19076.715, 19089.549) doing this basically crash the app with: -[MTLTextureDescriptorInternal validateWithDevice:]:1344: failed assertion `Texture Descriptor Validation MTLTextureDescriptor has height (16811) greater than the maximum allowed size of 8192. what am I doing wrong?
Replies
4
Boosts
2
Views
1.9k
Activity
Dec ’22
Charts: If I have one value on my x axis as a date, why is it showing time? Not the date?
Hi Folks, I’m noticing that the charts system I have presents the time of day that something was entered, if it’s a single value. Not the date. So for reference, my chart displays dollar value on the Y axis, and day that value was entered, on the X axis. if I have multiple values entered, it will display the dates. Cool. Although if it’s just one value, it displays the time it was entered, not the date. Which is not great. is there any way to adjust this so it displays the date, regardless of how many values are entered? Thsnks!
Replies
0
Boosts
0
Views
1k
Activity
Dec ’22
How to change the text color for SwiftUI Chart's legend text?
For a macOS app using Xcode 14.1. I have a bar chart with two bars for each interval. See screen chart below. I want to change the "Invoice" and Payments" text I can't seem to find a modifier for the Legend text. How do you change the text color for SwiftUI Chart's legend text?
Replies
3
Boosts
0
Views
3.5k
Activity
Nov ’22
Swift Charts Zoom
Is there a way to "zoom" a swift line chart with a gesture? For example like you zoom in and out in Maps. In this case you would would be changing the x or y axis scale as you pinch in or out.
Replies
3
Boosts
1
Views
3.2k
Activity
Nov ’22
SwiftUI Scrollable Charts in IOS16
Using the new SwiftUI Charts framework, we can make a chart bigger than the visible screen and place it into a ScrollView to make it scrollable. Something like this: var body : some View { GeometryReader { proxy in ScrollView(.horizontal, showsIndicators: false) { Chart { ForEach(data) { entry in // ... } } .frame(width: proxy.size.width * 2) } } } Does anybody know if it is possible to programmatically move the scroll to display a certain area of the chart? I've tried using ScrollViewReader, setting the IDs at the x-axis labels, and trying to use the scrollTo function to navigate to any of those positions with no luck: Chart { /// ... } .chartXAxis { AxisMarks(values: .stride(by: .day)) { value in if let date : Date = value.as(Date.self) { Text(date, style: .date) .font(.footnote) } } }
Replies
1
Boosts
1
Views
1.9k
Activity
Nov ’22
Revert yAxis values to start at the top with lowest values
Is it possible to revert the yAxis values to have the lowest numbers start from the top?
Replies
2
Boosts
0
Views
1.5k
Activity
Nov ’22
Chart styling question
How do I make the chart linemark and areamark extend to the edges of the plot area? I have looked at the Food Truck app and can't find how it is achieved. The screenshot attached points to the gaps I'd like to eliminate.
Replies
2
Boosts
0
Views
1.1k
Activity
Nov ’22
Swift Charts Interactive Scaling
I currently have a bar chart using Xcodes built in charts. I would like to make it so when I drag over an individual cell, that cell will increase it's width so that the user knows that is the cell they are selecting. How would I go about getting this effect. Thanks
Replies
0
Boosts
0
Views
855
Activity
Nov ’22
[Swift Charts] custom LineMark symbol is transparent
I have the following Chart and I can't figure out why the AreaMark's are transparent. The area marks are opaque when I move the .symbol view modifier to the AreaMark, but then the gradient doesn't work anymore Any ideas on how to solve this? struct Ranking: Identifiable {     let name: String     let steps: Int     var id: String { name } } let rankings: [Ranking] = [     .init(name: "Tom", steps: 200),     .init(name: "Joseph", steps: 850),     .init(name: "Emil", steps: 700),     .init(name: "Sandra", steps: 100),     .init(name: "Annie", steps: 400),     .init(name: "Teo", steps: 700),     .init(name: "Pär", steps: 400) ] struct ContentView: View {     let curGradient = LinearGradient(         gradient: Gradient (             colors: [                 Color(.blue).opacity(0.1),                 Color(.blue).opacity(0.0)             ]         ),         startPoint: .top,         endPoint: .bottom     )     var body: some View {         VStack() {             Text("Ranking")             Chart {                 ForEach(rankings) { element in                     LineMark(                         x: .value("Name", element.name),                         y: .value("Steps", element.steps)                     )                     .interpolationMethod(.catmullRom)                     .foregroundStyle(.blue)                     .symbol {                         Circle()                             .fill(.white)                             .frame(width: 20)                             .shadow(radius: 2)                     }                     AreaMark(                         x: .value("Name", element.name),                         y: .value("Steps", element.steps)                     )                     .interpolationMethod(.catmullRom)                     .foregroundStyle(curGradient)                 }             }             .chartYAxis(.hidden)             .chartXAxis {                 AxisMarks(position: .top) { value in                     AxisValueLabel(verticalSpacing: 20)                 }             }             .frame(height: 200)             Spacer()         }     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView()     } }
Replies
3
Boosts
0
Views
3.1k
Activity
Oct ’22
How do I remove the background lines of a chart
Hello, how do I remove the background lines of a chart and just show the BarMark? import SwiftUI import Charts struct myView: View { var body: some View {  Chart{   BarMark(x: .value("o", 5), y: .value("m", "Duration: 5m"), width: 7) .foregroundStyle(.orange) BarMark(x: .value("o", 7), y: .value("m", "Intervals: 7"), width: 7) .foregroundStyle(.teal)       } } }
Replies
3
Boosts
0
Views
4.1k
Activity
Oct ’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.8k
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
5k
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.8k
Activity
Sep ’22