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

SwiftUI Charts Issue - Axis Marks
I'm having an issue with SwiftUI charts and was wondering if anyone knows of a solution or has also run into this. I've been trying to plot data for my app and the X axis does not show the dates and the Y axis only has axis marks 0-9. So, I tried to make another file instance to check what's going on. This is what I have import Charts import SwiftUI struct Exercise: Identifiable { let id = UUID() var dateCompleted: Date var reps: Int } struct ContentView: View { private var exerciseMaxRepsArray: [Exercise] = [] init() { // init dummy data for i in 0 ..< 20 { let date = Calendar.current.date(byAdding: .day, value: i, to: .now) ?? .now let rep = Int.random(in: 1...20) exerciseMaxRepsArray.append( Exercise(dateCompleted: date, reps: rep) ) } } var body: some View { GroupBox(label: Text("Daily Max Reps")) { Chart(exerciseMaxRepsArray) { e in LineMark(x: .value("Date", e.dateCompleted, unit: .day), y: .value("Reps", e.reps) ) } .chartYAxisLabel(position: .trailing, alignment: .center) { Text("Reps") } .chartXAxisLabel(position: .bottom, alignment: .center) { Text("Date") } } and this is the result: I've checked and the issue is not the frame. Has anyone else had this issue or have any clue what could be going on here?
1
0
2.2k
Feb ’23
Swift Charts use custom font for legend
We have a custom font we use through-out our app we've recently starting playing with Swift Charts but can't work out how to use our font in the chart legend easily. Currently we have a simple chart using the default .chartLegend(...). I've managed to use our font in the X-axis and Y-axis by creating our own labels using AxisValueLabel() {} However without making our own completely custom legend, is there a way to specify the font to use in the legend?
0
0
1.2k
Jan ’23
Charts: How do I position x axis value labels below the associated grid lines
I am working with the new Charts Framework. The axis value labels for the x axis are dates (mm/dd/yy). I have 5 vertical grid lines and am trying to get the dates to be centered below the associated grid line with no success. One additional problem is that the values are in an array that contains 5 dates but only the first 4 get displayed. Any solutions will be appreciated. Below is the code. struct LineChart: View { private var localArray: [TradingDayPrices] init(passedInArray: [TradingDayPrices]) { self.localArray = passedInArray } var body: some View { let minCloseValue: Double = localArray.map { $0.close }.min()! let maxCloseValue: Double = localArray.map { $0.close }.max()! let minDate: Date = localArray[0].timeStamp! let itemCount: Int = localArray.count - 1 let maxDate: Date = localArray[itemCount].timeStamp! Spacer() GroupBox (label: Text("VOO Closing Values For The Past Year") .font(.system(size: 20)) .fontWeight(.bold) .frame(width: 700, height: 50, alignment: .center)) { Chart { ForEach(localArray) { item in LineMark ( x: .value("TimeStamp", item.timeStamp!), y: .value("Close", item.close) ) .foregroundStyle(Color.blue) .lineStyle(StrokeStyle(lineWidth: 1.25)) } // end for each } // end chart .padding(50) .chartBackground { item in Color.white } .chartXAxisLabel(position: .bottom, alignment: .center) { Text("Date") .font(.system(size: 14)) .foregroundColor(Color.black) .frame(width: 50, height: 35, alignment: .bottom) } .chartYAxisLabel(position: .leading, alignment: .center, spacing: 0) { Text("Closing Values") .font(.system(size: 14)) .foregroundColor(Color.black) } .chartXAxis { AxisMarks (values: GetXAxisLabels(min: minDate, max: maxDate)) { value in AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5)) .foregroundStyle(Color.gray) AxisValueLabel() { if let localDate = value.as(Date.self) { let formattedDate = dateToStringFormatter.string(from: localDate) Text(formattedDate) .font(.system(size: 12)) .foregroundColor(Color.black) } } // end axis value label } // end axis marks } // end chart x axis .chartYAxis { AxisMarks (position: .leading, values: GetYAxisLabels(min: minCloseValue, max: maxCloseValue)) { value in AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5)) .foregroundStyle(Color.gray) AxisValueLabel() { if let localValue = value.as(Double.self) { let formattedValue = String(format: "$%.2f", localValue) Text(formattedValue) .font(.system(size: 12)) .foregroundColor(Color.black) } } } // end axis marks } // end chart y axis .chartXScale(domain: minDate...maxDate) .chartYScale(domain: minCloseValue...maxCloseValue) .frame(width: 700, height: 700, alignment: .center) } // end group box } // end of body } // end of structure func GetXAxisLabels(min: Date, max: Date) -> [Date] { var xLabels: [Date] = [] let increment: Int = 90 for i in 0...3 { let value = Calendar.current.date(byAdding: DateComponents(day: (i * increment)), to: min)! xLabels.append(value) } xLabels.append(max) print("\(xLabels)") return xLabels } func GetYAxisLabels(min: Double, max: Double) -> [Double] { var yLabels: [Double] = [] let increment: Double = (max - min) / 4 for i in 0...3 { let value = min + (Double(i) * increment) yLabels.append(value) } yLabels.append(max) return yLabels } let dateToStringFormatter: DateFormatter = { let result = DateFormatter() result.dateFormat = "MM/dd/yy" return result }()
2
1
4k
Jan ’23
SwiftUI Charts - Bar Chart (side by side) (not stacked), proxy value not working
Create a bar Chart with data displayed (side by side) instead of default (stacked bar chart) (using .position modifier) Issue: chart proxy value cannot find any value. If I change to stacked bar chart, then proxy value works ok. Sample code:-             Chart() {                 ForEach(barchartdata, id:\.self) { one_row in                     BarMark(                         x: .value("Date", one_row.shortDate),                         y: .value("$", one_row.steps)                     )   // LineMark                     .foregroundStyle(by: .value("Name", one_row.name))                     .symbol(by: .value("Name", one_row.name))                     .interpolationMethod(.catmullRom)                     .position(by: .value("Name", one_row.name))                 }             }             .chartPlotStyle { plotArea in                 plotArea                     .frame(width: UIScreen.main.bounds.size.width * 6/8)                     .background(.blue.opacity(0.2))                     .border(.blue, width: 1)             }             .chartOverlay { proxy in                 GeometryReader { geometry in                     RoundedRectangle(cornerRadius : 5)                         .fill(.clear)                         .contentShape(Rectangle())                         .onTapGesture { location in                             updateSelectedMonth(location: location, proxy: proxy, geometry: geometry)                         }  // onTapGesture                                     }             } ....     func updateSelectedMonth(location : CGPoint, proxy: ChartProxy, geometry : GeometryProxy) { let local_location = CGPoint(             x: location.x - geometry[proxy.plotAreaFrame].origin.x,             y: location.y - geometry[proxy.plotAreaFrame].origin.y)         let (sel_date, sel_steps) = proxy.value(at: local_location, as: (Date, Int64).self) ?? (nil,nil) }
0
1
2.2k
Jan ’23
Chart moves itself unintentionally with a big frame size
I try to make an interactive chart view. However, in a specific condition, the chart moves iteself unintentionally. In my test code, this phenomenon occurs when the frame width is over 652.5. (And, this is also relevant to the height) Test Movie OK: NG: If you are OK, could you tell me what is a problem in my code? My test code is the followings: import SwiftUI import Charts struct ContentView: View {   @State var chartW = 652.45   @State var basisDate: Date = Date2StartOnADay(date: Date())   @State var dateRange: Double = 7   @State var dateB = Date2StartOnADay(date: Date()).addingTimeInterval(Double(-7*24*60*60))   @State var dateE = Date2StartOnADay(date: Date())   var body: some View {     VStack {       Slider(value: $chartW, in: 652.45 ... 652.55)       Text("\(chartW)")       DailyChartView(dateB: $dateB, dateE: $dateE, basisDate: $basisDate, dateRange: $dateRange)         .frame(width: chartW, height: 300)     }   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } } struct DailyChartView: View {   @Binding var dateB: Date   @Binding var dateE: Date   @Binding var basisDate: Date   @Binding var dateRange: Double   var yMin: Double = 0.0   var yMax: Double = 100.0   var isFixedYRange: Bool = true   @State var dt: TimeInterval?       var body: some View {     Chart {       AreaMark(x: .value("date", Date().addingTimeInterval(-2*24*60*60)),            y: .value("value", 10)       )       AreaMark(x: .value("date", Date().addingTimeInterval(-24*60*60)),            y: .value("value", 50)       )       AreaMark(x: .value("date", Date()),            y: .value("value", 20)       )       AreaMark(x: .value("date", Date().addingTimeInterval(24*60*60)),            y: .value("value", 70)       )     }     .chartXScale(domain: dateB ... dateE)     .chartYScale(domain: yMin ... yMax)     .chartOverlay { proxy in       GeometryReader { geometry in         Rectangle().fill(.clear).contentShape(Rectangle())           .gesture(DragGesture(minimumDistance: 8)             .onChanged {value in               let startX = value.startLocation.x - geometry[proxy.plotAreaFrame].origin.x               let currentX = value.location.x - geometry[proxy.plotAreaFrame].origin.x               if let startDate: Date = proxy.value(atX: startX),                 let currentDate: Date = proxy.value(atX: currentX) {                 dt = currentDate.timeIntervalSince(startDate)                 dateB = basisDate.addingTimeInterval(-dateRange*24*60*60-dt!)                 dateE = basisDate.addingTimeInterval(-dt!)               }             }             .onEnded {_ in               basisDate = dateE             }           )       }     }     .clipped()   } } func Date2StartOnADay(date: Date) -> Date {   let cal = Calendar(identifier: .gregorian)   let comp = cal.dateComponents(     [Calendar.Component.year, Calendar.Component.month, Calendar.Component.day,      Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second, Calendar.Component.nanosecond],      from: date)   let startOnADay = cal.date(from: DateComponents(year: comp.year!, month: comp.month!, day: comp.day))   return startOnADay! }
0
0
821
Jan ’23
interpolating AreaMarks beyond the edge of the chart
I'm making an app that shows tides. It's approximately a sine wave going smoothly in and out. If I use only the low and high tides times, the line should curve slowly between them. If the first value on the chart is a low tide and the next is a high tide I want the line to start from horizontal, get steeper and then flatten out as the tide peaks. This happens for all the values within the chart except for the first and last because there's no data outside of the chart's range to tell the interpolation code where the line needs to curve to. If I add extra data beyond what I am displaying, the chart adapts and shows that data too, then I have nothing beyond that. Some pictures might help Here the first and last points look like the tide is still going down/up rather fast, where as the other points all slow down as they reach the high/low value I tried using .chartXScale(domain: start...end) to set the bounds of the x-axis, but the chart gets drawn beyond those bounds I believe I can fake it by adding my own interpolated points just seconds before the first and after the last point with the same value as the true data. This would force the interpolation to flatten out, but I'd rather use the real data and control the chart sounds properly
0
0
1k
Jan ’23
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.5k
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
2.0k
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.2k
Oct ’22
SwiftUI Charts Issue - Axis Marks
I'm having an issue with SwiftUI charts and was wondering if anyone knows of a solution or has also run into this. I've been trying to plot data for my app and the X axis does not show the dates and the Y axis only has axis marks 0-9. So, I tried to make another file instance to check what's going on. This is what I have import Charts import SwiftUI struct Exercise: Identifiable { let id = UUID() var dateCompleted: Date var reps: Int } struct ContentView: View { private var exerciseMaxRepsArray: [Exercise] = [] init() { // init dummy data for i in 0 ..< 20 { let date = Calendar.current.date(byAdding: .day, value: i, to: .now) ?? .now let rep = Int.random(in: 1...20) exerciseMaxRepsArray.append( Exercise(dateCompleted: date, reps: rep) ) } } var body: some View { GroupBox(label: Text("Daily Max Reps")) { Chart(exerciseMaxRepsArray) { e in LineMark(x: .value("Date", e.dateCompleted, unit: .day), y: .value("Reps", e.reps) ) } .chartYAxisLabel(position: .trailing, alignment: .center) { Text("Reps") } .chartXAxisLabel(position: .bottom, alignment: .center) { Text("Date") } } and this is the result: I've checked and the issue is not the frame. Has anyone else had this issue or have any clue what could be going on here?
Replies
1
Boosts
0
Views
2.2k
Activity
Feb ’23
Swift Charts use custom font for legend
We have a custom font we use through-out our app we've recently starting playing with Swift Charts but can't work out how to use our font in the chart legend easily. Currently we have a simple chart using the default .chartLegend(...). I've managed to use our font in the X-axis and Y-axis by creating our own labels using AxisValueLabel() {} However without making our own completely custom legend, is there a way to specify the font to use in the legend?
Replies
0
Boosts
0
Views
1.2k
Activity
Jan ’23
Charts: How do I position x axis value labels below the associated grid lines
I am working with the new Charts Framework. The axis value labels for the x axis are dates (mm/dd/yy). I have 5 vertical grid lines and am trying to get the dates to be centered below the associated grid line with no success. One additional problem is that the values are in an array that contains 5 dates but only the first 4 get displayed. Any solutions will be appreciated. Below is the code. struct LineChart: View { private var localArray: [TradingDayPrices] init(passedInArray: [TradingDayPrices]) { self.localArray = passedInArray } var body: some View { let minCloseValue: Double = localArray.map { $0.close }.min()! let maxCloseValue: Double = localArray.map { $0.close }.max()! let minDate: Date = localArray[0].timeStamp! let itemCount: Int = localArray.count - 1 let maxDate: Date = localArray[itemCount].timeStamp! Spacer() GroupBox (label: Text("VOO Closing Values For The Past Year") .font(.system(size: 20)) .fontWeight(.bold) .frame(width: 700, height: 50, alignment: .center)) { Chart { ForEach(localArray) { item in LineMark ( x: .value("TimeStamp", item.timeStamp!), y: .value("Close", item.close) ) .foregroundStyle(Color.blue) .lineStyle(StrokeStyle(lineWidth: 1.25)) } // end for each } // end chart .padding(50) .chartBackground { item in Color.white } .chartXAxisLabel(position: .bottom, alignment: .center) { Text("Date") .font(.system(size: 14)) .foregroundColor(Color.black) .frame(width: 50, height: 35, alignment: .bottom) } .chartYAxisLabel(position: .leading, alignment: .center, spacing: 0) { Text("Closing Values") .font(.system(size: 14)) .foregroundColor(Color.black) } .chartXAxis { AxisMarks (values: GetXAxisLabels(min: minDate, max: maxDate)) { value in AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5)) .foregroundStyle(Color.gray) AxisValueLabel() { if let localDate = value.as(Date.self) { let formattedDate = dateToStringFormatter.string(from: localDate) Text(formattedDate) .font(.system(size: 12)) .foregroundColor(Color.black) } } // end axis value label } // end axis marks } // end chart x axis .chartYAxis { AxisMarks (position: .leading, values: GetYAxisLabels(min: minCloseValue, max: maxCloseValue)) { value in AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5)) .foregroundStyle(Color.gray) AxisValueLabel() { if let localValue = value.as(Double.self) { let formattedValue = String(format: "$%.2f", localValue) Text(formattedValue) .font(.system(size: 12)) .foregroundColor(Color.black) } } } // end axis marks } // end chart y axis .chartXScale(domain: minDate...maxDate) .chartYScale(domain: minCloseValue...maxCloseValue) .frame(width: 700, height: 700, alignment: .center) } // end group box } // end of body } // end of structure func GetXAxisLabels(min: Date, max: Date) -> [Date] { var xLabels: [Date] = [] let increment: Int = 90 for i in 0...3 { let value = Calendar.current.date(byAdding: DateComponents(day: (i * increment)), to: min)! xLabels.append(value) } xLabels.append(max) print("\(xLabels)") return xLabels } func GetYAxisLabels(min: Double, max: Double) -> [Double] { var yLabels: [Double] = [] let increment: Double = (max - min) / 4 for i in 0...3 { let value = min + (Double(i) * increment) yLabels.append(value) } yLabels.append(max) return yLabels } let dateToStringFormatter: DateFormatter = { let result = DateFormatter() result.dateFormat = "MM/dd/yy" return result }()
Replies
2
Boosts
1
Views
4k
Activity
Jan ’23
SwiftUI Charts - Bar Chart (side by side) (not stacked), proxy value not working
Create a bar Chart with data displayed (side by side) instead of default (stacked bar chart) (using .position modifier) Issue: chart proxy value cannot find any value. If I change to stacked bar chart, then proxy value works ok. Sample code:-             Chart() {                 ForEach(barchartdata, id:\.self) { one_row in                     BarMark(                         x: .value("Date", one_row.shortDate),                         y: .value("$", one_row.steps)                     )   // LineMark                     .foregroundStyle(by: .value("Name", one_row.name))                     .symbol(by: .value("Name", one_row.name))                     .interpolationMethod(.catmullRom)                     .position(by: .value("Name", one_row.name))                 }             }             .chartPlotStyle { plotArea in                 plotArea                     .frame(width: UIScreen.main.bounds.size.width * 6/8)                     .background(.blue.opacity(0.2))                     .border(.blue, width: 1)             }             .chartOverlay { proxy in                 GeometryReader { geometry in                     RoundedRectangle(cornerRadius : 5)                         .fill(.clear)                         .contentShape(Rectangle())                         .onTapGesture { location in                             updateSelectedMonth(location: location, proxy: proxy, geometry: geometry)                         }  // onTapGesture                                     }             } ....     func updateSelectedMonth(location : CGPoint, proxy: ChartProxy, geometry : GeometryProxy) { let local_location = CGPoint(             x: location.x - geometry[proxy.plotAreaFrame].origin.x,             y: location.y - geometry[proxy.plotAreaFrame].origin.y)         let (sel_date, sel_steps) = proxy.value(at: local_location, as: (Date, Int64).self) ?? (nil,nil) }
Replies
0
Boosts
1
Views
2.2k
Activity
Jan ’23
Chart moves itself unintentionally with a big frame size
I try to make an interactive chart view. However, in a specific condition, the chart moves iteself unintentionally. In my test code, this phenomenon occurs when the frame width is over 652.5. (And, this is also relevant to the height) Test Movie OK: NG: If you are OK, could you tell me what is a problem in my code? My test code is the followings: import SwiftUI import Charts struct ContentView: View {   @State var chartW = 652.45   @State var basisDate: Date = Date2StartOnADay(date: Date())   @State var dateRange: Double = 7   @State var dateB = Date2StartOnADay(date: Date()).addingTimeInterval(Double(-7*24*60*60))   @State var dateE = Date2StartOnADay(date: Date())   var body: some View {     VStack {       Slider(value: $chartW, in: 652.45 ... 652.55)       Text("\(chartW)")       DailyChartView(dateB: $dateB, dateE: $dateE, basisDate: $basisDate, dateRange: $dateRange)         .frame(width: chartW, height: 300)     }   } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()   } } struct DailyChartView: View {   @Binding var dateB: Date   @Binding var dateE: Date   @Binding var basisDate: Date   @Binding var dateRange: Double   var yMin: Double = 0.0   var yMax: Double = 100.0   var isFixedYRange: Bool = true   @State var dt: TimeInterval?       var body: some View {     Chart {       AreaMark(x: .value("date", Date().addingTimeInterval(-2*24*60*60)),            y: .value("value", 10)       )       AreaMark(x: .value("date", Date().addingTimeInterval(-24*60*60)),            y: .value("value", 50)       )       AreaMark(x: .value("date", Date()),            y: .value("value", 20)       )       AreaMark(x: .value("date", Date().addingTimeInterval(24*60*60)),            y: .value("value", 70)       )     }     .chartXScale(domain: dateB ... dateE)     .chartYScale(domain: yMin ... yMax)     .chartOverlay { proxy in       GeometryReader { geometry in         Rectangle().fill(.clear).contentShape(Rectangle())           .gesture(DragGesture(minimumDistance: 8)             .onChanged {value in               let startX = value.startLocation.x - geometry[proxy.plotAreaFrame].origin.x               let currentX = value.location.x - geometry[proxy.plotAreaFrame].origin.x               if let startDate: Date = proxy.value(atX: startX),                 let currentDate: Date = proxy.value(atX: currentX) {                 dt = currentDate.timeIntervalSince(startDate)                 dateB = basisDate.addingTimeInterval(-dateRange*24*60*60-dt!)                 dateE = basisDate.addingTimeInterval(-dt!)               }             }             .onEnded {_ in               basisDate = dateE             }           )       }     }     .clipped()   } } func Date2StartOnADay(date: Date) -> Date {   let cal = Calendar(identifier: .gregorian)   let comp = cal.dateComponents(     [Calendar.Component.year, Calendar.Component.month, Calendar.Component.day,      Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second, Calendar.Component.nanosecond],      from: date)   let startOnADay = cal.date(from: DateComponents(year: comp.year!, month: comp.month!, day: comp.day))   return startOnADay! }
Replies
0
Boosts
0
Views
821
Activity
Jan ’23
interpolating AreaMarks beyond the edge of the chart
I'm making an app that shows tides. It's approximately a sine wave going smoothly in and out. If I use only the low and high tides times, the line should curve slowly between them. If the first value on the chart is a low tide and the next is a high tide I want the line to start from horizontal, get steeper and then flatten out as the tide peaks. This happens for all the values within the chart except for the first and last because there's no data outside of the chart's range to tell the interpolation code where the line needs to curve to. If I add extra data beyond what I am displaying, the chart adapts and shows that data too, then I have nothing beyond that. Some pictures might help Here the first and last points look like the tide is still going down/up rather fast, where as the other points all slow down as they reach the high/low value I tried using .chartXScale(domain: start...end) to set the bounds of the x-axis, but the chart gets drawn beyond those bounds I believe I can fake it by adding my own interpolated points just seconds before the first and after the last point with the same value as the true data. This would force the interpolation to flatten out, but I'd rather use the real data and control the chart sounds properly
Replies
0
Boosts
0
Views
1k
Activity
Jan ’23
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.5k
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
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
2.0k
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] 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.2k
Activity
Oct ’22