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

29 Posts

Post

Replies

Boosts

Views

Activity

How to display numbers as grid marks along axes for plotting in Swift Charts?
If you try to add a graph for a function in Apple Notes you can see that numbers marking coordinates are positioned along the axes (see screenshot 1). But when I am making my own plot view with Swift Charts I don't see that option. Marks for X axis are positioned at the bottom, and marks for Y axis are positioned to the right. I don't see an API that can configure them to be shown along the axes. Is there something that I am missing? Or is Apple just using some private API for that? I could make a custom overlay to display these marks, but then I will have to adjust them while zooming myself, which can be problematic.
1
0
68
Jun ’25
How to get the date range of the data that is currently displayed in a Apple Chart?
I have a Swiftui app, and I'm using the Apple Chart framework to chart user transactions over time. I'd like to be able to show an annotation at the top of the chart that shows the date range of the records currently visible on the chart. Much like Apple does in their Heath App charts. But I just can't seem to find a method to read the current date range displayed on the chart once the user has scrolled though the chart. Has anyone done anything similar, or maybe seen some sample code? So far I'm striking out on this... Thanks in advance
1
0
71
May ’25
chartXAxis AxisMark consisting of Month:Year
I have a Chart displaying Counts per Date over 2-3 years. I'd like to have the XAxis mark consist of MM-yy or even MM/nyy. Is this possible? OK, just saw AxisValueLabel(format: .dateTime.month().year()) which gives e.g. Mar 2024. This is good. Better might be Mar 24 (maybe a Y3K problem ;-) or even better Mar. OR Mar 24. 2024 Or best increment the year when it changes. Are any of these alternate formats possible? Thanks, David PS, my current .chartXAxis code .chartXAxis { AxisMarks(values: .stride(by: .month, count: 3)) { value in if value.as(Date.self) != nil { AxisValueLabel(format: .dateTime.month().year()) AxisGridLine() AxisTick() } } }
1
0
85
Jun ’25
How to have different colors in Charts with AreaMark
I would like to have different fill colors in my chart. What I want to achieve is that if the values drop below 0 the fill color should be red. If they are above the fill color should be red. My code looks as follows: import SwiftUI import Charts struct DataPoint: Identifiable {     let id: UUID = UUID()     let x: Int     let y: Int } struct AlternatingChartView: View {          enum Gradients {         static let greenGradient = LinearGradient(gradient: Gradient(colors: [.green, .white]), startPoint: .top, endPoint: .bottom)         static let blueGradient = LinearGradient(gradient: Gradient(colors: [.white, .blue]), startPoint: .top, endPoint: .bottom)     }          let data: [DataPoint] = [         DataPoint(x: 1, y: 10),         DataPoint(x: 2, y: -5),         DataPoint(x: 3, y: 20),         DataPoint(x: 4, y: -8),         DataPoint(x: 5, y: 15),     ]               var body: some View {         Chart {             ForEach(data) { data in                 AreaMark(                     x: .value("Data Point", data.x),                     y: .value("amount", data.y))                 .interpolationMethod(.catmullRom)                 .foregroundStyle(data.y < 0 ? Color.red : Color.green)                                  LineMark(                 x: .value("Data Point", data.x),                 y: .value("amount", data.y))                 .interpolationMethod(.catmullRom)                 .foregroundStyle(Color.black)                 .lineStyle(StrokeStyle.init(lineWidth: 4))                              }         }         .frame(height: 200)     } } #Preview {     AlternatingChartView() } The result looks like this: I also tried using foregroundStyle(by:) and chartForegroundStyleScale(_:) but the result was, that two separate areas had been drawn. One for the below and one for the above zero datapoints. So, what would be the right approach to have two different fill colors?
0
0
66
Jun ’25
Using .glassEffect in Charts
Hi, I was wondering if it's possible (and advisable) to use the new glass effects available in iOS 26 in Swift Charts? For example, in a chart like the one in the image I've attached to this post, I was looking to try adding a .glassEffect modifier to the BarMarks to see how that would look and feel. However, it seems it's not available directly on the BarMark (ChartContent) type, and I'm having trouble adding it in other ways too, such as using in on the types I supply to modifiers like foregroundStyle or clipShape. Am I missing anything? Maybe it's just not advisable or necessary to use glass effects within Charts?
5
0
219
Aug ’25
.chartScrollableAxes(.horizontal) prevents chartYAxisLabel from being postioned top right, over Y axis
Adding .chartScrollableAxes(.horizontal) to a chart prevents chartYAxisLabel from being positioned top right, over Y axis. We want the label at top right, over the Y-axis, but with chartScrollableAxes it is always top right relative to the initial chartXVisibleDomain, which puts it in the middle of the chart if chartXVisibleDomain < full x domain. import SwiftUI import Charts struct ContentView: View { @State private var numbers = (0..<100) .map { _ in Double.random(in: 0...100) } @State var visibleDomain : Int = 50 var body: some View { Chart(Array(zip(numbers.indices, numbers)), id: \.1) { index, number in LineMark( x: .value("Index", index), y: .value("Number", number) ) } .chartScrollableAxes(.horizontal) .chartXVisibleDomain(length: visibleDomain) .chartScrollPosition(initialX: 70) .chartYAxisLabel(position: .topTrailing, alignment: .center) { /* We want the label at top right, over the Y-axis, but with chartScrollableAxes it is always top right relative to the initial chartXVisibleDomain, which puts it in the middle of the chart if chartXVisibleDomain < full x domain */ Text("units") .foregroundStyle(.red) .fontWeight(.bold) } .padding() } } #Preview { ContentView() }
1
0
55
Jun ’25
How to read a value when tapping a point on a Chart3D
Hi. Chart3D seems to be perfect to visualize a chart on one of my apps. However I would need a way to read the point of a SurfacePlot of a Chart3D that was touched by the user? Something like a Chart .chartOverlay that has a ChartProxy that can convert screen coordinates of the chart in values, but in 3D (maybe using hit testing ). Thanks and best regards. João Colaço
2
0
79
Jun ’25
Charts SectorMark causing app to crash
Anytime I have 1 item, then add another, the app crashes with the following error: Swift/IntegerTypes.swift:8835: Fatal error: Double value cannot be converted to Int because it is either infinite or NaN I'm not working with Int values though, so I'm not sure why this is happening. It's also not point me towards any specific line. I've printed out all of the values being used for the chart and none of them are showing as infinite or NaN. The data being used is created in a View. @State private var pieChartData: [PieChartDataPoint] = [] Then in the onAppear and onChange its gets loaded using the following function: func getPieChartDataPoints() -> [PieChartDataPoint] { self.map({ PieChartDataPoint(label: $0.name, value: $0.monthlyAmount()) }) } That's an extension on a SwiftData model type I have called Recurring. @Model final class Recurring { var id = UUID() enum Kind: String, CaseIterable, Codable { case income = "Income" case bill = "Bill" func plural() -> String { switch self { case .income: "Income" case .bill: "Bills" } } } enum Frequency: String, CaseIterable, Codable, Identifiable { var id: Frequency { self } case weekly = "Weekly" case biweekly = "Biweekly" case monthly = "Monthly" case quarterly = "Quarterly" case annually = "Annually" } var name: String = "" var kind: Kind = Kind.income var frequency: Frequency = Frequency.biweekly var amount: Double = 0 init(name: String, kind: Kind, frequency: Frequency, amount: Double) { self.name = name self.kind = kind self.frequency = frequency self.amount = amount } func amount(from cycle: Cycle) -> Double { switch cycle { case .weekly: monthlyAmount() * 12 / 52 case .biweekly: monthlyAmount() * 12 / 26 case .monthly: monthlyAmount() } } func monthlyAmount() -> Double { switch frequency { case .weekly: amount * 52 / 12 case .biweekly: amount * 26 / 12 case .monthly: amount case .quarterly: amount * 4 / 12 case .annually: amount / 12 } } } Here is the DataPoint structure. struct PieChartDataPoint: Identifiable, Equatable { var id = UUID() var label: String var value: Double } Finally here is the chart. Chart(sorted, content: { dataPoint in SectorMark( angle: .value(dataPoint.label, getValue(from: dataPoint)), innerRadius: 50, angularInset: 5 ) .foregroundStyle(by: .value("Label", dataPoint.label)) .cornerRadius(10) .opacity(getSectorMarkOpacity(for: dataPoint)) }) .scaledToFill() .chartLegend(.hidden) .chartAngleSelection(value: $chartSelection) .onChange(of: chartSelection, checkSelection) For testing purposes, I have removed all of the modifiers and only had a simple SectorMark in the Chart, however, that was still crashing. Does anyone know why this is happening?
1
0
67
Aug ’25
macOS 26: retain cycle detected when navigation link label contains a Swift Chart
I'm running into an issue where my application will hang when switching tabs. The issue only seems to occur when I include a Swift Chart in a navigation label. The application does not hang If I replace the chart with a text field. This appears to only hang when running on macOS 26. When running on iOS (simulator) or visionOS (simulator, on-device) I do not observe a hang. The same code does not hang on macOS 15. Has any one seen this behavior? The use case is that my root view is a TabView where the first tab is a summary of events that have occurred. This summary is embedded in a NavigationStack and has a graph of events over the last week. I want the user to be able to click that graph to get additional information regarding the events (ie: a detail page or break down of events). Initially, the summary view loads fine and displays appropriately. However, when I switch to a different tab, the application will hang when I switch back to the summary view tab. In Xcode I see the following messages === AttributeGraph: cycle detected through attribute 162104 === === AttributeGraph: cycle detected through attribute 162104 === === AttributeGraph: cycle detected through attribute 162104 === === AttributeGraph: cycle detected through attribute 162104 === === AttributeGraph: cycle detected through attribute 162104 === A simple repro is the following import SwiftUI import Charts @main struct chart_cycle_reproApp: App { var body: some Scene { WindowGroup { TabView { Tab("Chart", systemImage: "chart.bar") { NavigationStack { NavigationLink { Text("this is an example of clicking the chart") } label: { Chart { BarMark( x: .value("date", "09/03"), y: .value("birds", 3) ) // additional marks trimmed } .frame(minHeight: 200, maxHeight: .infinity) } } } Tab("List", systemImage: "list.bullet") { Text("This is an example") } } } } }
0
0
146
Sep ’25