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

SwiftUI charts, how do I align these X axis labels correctly?
Hi there, so I have this chart that's taking in a Date for it's x values and a time interval for their y values. For some reason, the labels aren't centering on each bar, the only fix I see is to add an offset to each label but that seems hacky. My code: Chart { ForEach(weekBreakdownArr, id: \.startDate) { bd in BarMark( x: .value("Date", bd.startDate), y: .value("Duration", bd.durationWorkDone), width: .fixed(15) ) .foregroundStyle(Color.redYarn) .cornerRadius(2) } //... } // shownXValues are just the start dates in an array .chartXAxis { AxisMarks(position: .automatic, values: shownXValues) { val in AxisValueLabel { Text("Th") .useAppFont(size: 12, relativeTo: .body, weight: .regular) } } }
1
0
771
Dec ’24
Swift Charts legend overflowing outside frame
I'm building an app that lets users create charts with custom values and while testing, I came up with this bug that happens when the view width forces the legend to have more than 1 line. Due to Swift trying to align the different labels vertically, it's forcing the first line to overflow. Here's the code to generate this: import SwiftUI import Charts struct DonutView: View { var countries:[(country:String, count:Int)] = [ (country: "Africa", count: 54), (country: "Asia", count: 48), (country: "Europe", count: 44), (country: "North America", count: 23), (country: "Oceania", count: 14), (country: "South America", count: 12), ] var body: some View { Chart { ForEach(0..<countries.count, id:\.self) { idx in SectorMark( angle: .value(countries[idx].country, countries[idx].count), innerRadius: .ratio(0.5) ) .foregroundStyle(by: .value("label", countries[idx].country)) } } .frame(width: 310, height: 270) .border(.blue, width: 1) } } Has anyone seen this? Is there a solution? I know about building custom legends, but SwiftUI has no wrapping HStack nor VStack, and the app allows users to change the legend position from the bottom to the top or sides. If I were to go this way, I'd have to write a very large chunk of code to bypass what seems to be a bug.
1
0
597
Dec ’24
Swift Charts: chartScrollTargetBehavior fails to snap to a day unit
I am working on a scrollable chart that displays days on the horizontal axis. As the user scrolls, I always want them to be able to snap to a specific day. I implemented the following steps described in this WWDC23 session to achieve this. I have set the chartScrollTargetBehavior to .valueAligned(matching: DateComponents(hour: 0)) I have set the x value unit on the BarMark to Calendar.Component.day I ended up with the chart code that looks like this: Chart(dates, id: \.self) { date in BarMark( x: .value("Date", date, unit: Calendar.Component.day), y: .value("Number", 1) ) .annotation { Text(date.formatted(.dateTime.day())) .font(.caption2) } } .chartXAxis { AxisMarks(format: .dateTime.day()) } .chartScrollableAxes(.horizontal) .chartScrollTargetBehavior(.valueAligned(matching: DateComponents(hour: 0))) .chartXVisibleDomain(length: fifteenDays) .chartScrollPosition(x: $selection) However, this fails to work reliably. There is often a situation where the chart scroll position lands on, for instance, Oct 20, 11:56 PM, but the chart snaps to Oct 21. I attempted to solve this problem by introducing an intermediate binding between a state value and a chart selection. This binding aims to normalize the selection always to be the first moment of any given date. But this hasn't been successful. private var selectionBinding: Binding<Date> { Binding { Calendar.current.startOfDay(for: selection) } set: { newValue in self.selection = Calendar.current.startOfDay(for: newValue) } } It's also worth mentioning that this issue also exists in Apple's sample project on Swift Charts. How would you approach solving this? How can I find a way to make the chart scroll position blind to time values and only recognize whole days? Here's the minimal reproducible example project for your reference.
1
1
677
Nov ’24
Swift UI Chart Accessibility issue
Hi Team, We are integrating SwiftUI's Charts BarMark, UI looks good but when we try setting up custom ADA it doesn't reflect/override the accessibility label/value we set manually. Is it iOS defect or is there any workaround? Thanks in advance. Sample: Chart(data) { BarMark( x: .value("Category", $0.department), y: .value("Profit", $0.profit) ) .foregroundStyle(by: .value("Product Category", $0.productCategory)) .accessibilityIdentifier("BarMark") .accessibilityLabel("Dep: \($0.department)") .accessibilityValue("Profile: \($0.profit) Category: \($0.productCategory)") }
1
2
688
Nov ’24
Tranforming a chart's origin
Hi, I'm trying to create a visualization using charts for vision pro. I want to create a line chart that connects pair of points on a donut chart. So i'm trying to draw the lines radially but it seems that the line chart always has only the bottom left corner of the view as origin. How can I tranform the origin to center of the view?
Topic: Design SubTopic: General Tags:
1
0
714
Oct ’24
SwiftUI Charts not working in Xcode 16 Beta 2
Is there a way to workaround this issue? Can I revert back to Beta 1? Failed to build module 'Charts'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.7.41 clang-1600.0.24.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.11 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK.
2
1
1.1k
Oct ’24
Unable to compile SwiftUI Charts on Xcode 16.1 Beta 2
Unable to compile app that imports Swift UI Charts SDK on Xcode Version 16.1 beta 2 (16B5014f) with error: Failed to build module 'Charts'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.7.41 clang-1600.0.24.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.11 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK. FB15161667
5
15
2.5k
Oct ’24
Unable to import Charts in Xcode 16.1 beta 2
Failed to build module 'Charts'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.7.41 clang-1600.0.24.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.11 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK. Any fix yet?
2
2
833
Oct ’24
VoiceOver ignoring a data series when there are multiple ones
I can't figure out if I've found a VoiceOver problem with Swift Charts or if I'm doing something incorrectly. I have a loop within a loop showing 2 sets of data in the same chart. If I touch a month then VO correctly says there are two data series. But if I keep swiping down only data from the first series is read. ChatGPT said try referencing the outer loop and sure enough that worked if it done in BOTH the label and value. It sounds really awkward though. For example, "High 89 degrees F High October". Below the "bad" chart only says something such as "92 degrees F October" when swiping down. The "good" chart will read the high and low temperature data. VStack { headerText("BAD") Chart { ForEach(processedMonthlyInput) { oneMonth in ForEach(oneMonth.temperatures, id: \.month) { element in LineMark( x: .value("Month", element.month, unit: .month), y: .value("Temperature", element.tempVal.converted(to: .fahrenheit).value) ) .accessibilityLabel("\(element.month.formatted(.dateTime.month(.wide)))") .accessibilityValue(Text("\(element.tempVal.converted(to: tempUnit).formatted(.measurement(width: .abbreviated, numberFormatStyle: .number.precision(.fractionLength(0)))))")) } .symbol(by: .value("Type", oneMonth.theType)) .foregroundStyle(by: .value("Type", oneMonth.theType)) .interpolationMethod(.catmullRom) } } .frame(maxHeight: paddingAmount) .padding(.horizontal) headerText("GOOD") Chart { ForEach(processedMonthlyInput) { oneMonth in ForEach(oneMonth.temperatures, id: \.month) { element in LineMark( x: .value("Month", element.month, unit: .month), y: .value("Temperature", element.tempVal.converted(to: .fahrenheit).value) ) .accessibilityLabel("\(oneMonth.theType) \(element.month.formatted(.dateTime.month(.wide)))") .accessibilityValue(Text("\(oneMonth.theType) \(element.tempVal.converted(to: tempUnit).formatted(.measurement(width: .abbreviated, numberFormatStyle: .number.precision(.fractionLength(0)))))")) } .symbol(by: .value("Type", oneMonth.theType)) .foregroundStyle(by: .value("Type", oneMonth.theType)) .interpolationMethod(.catmullRom) } } .frame(maxHeight: paddingAmount) .padding(.horizontal) }
0
0
590
Sep ’24
Swift Charts performance when displaying many data points
I'm currently evaluating Swift Charts to use in my macOS app, where I need to (potentially) display a few millions of data points, ideally all of them at one time. I want to give users the possibility to zoom in & out, so the entire range of values could be displayed at one moment. However, starting at around 20K data points (on my computer), the Chart takes a little bit to set up, but the window resizing is laggy. The performance seems to decrease linearly (?), when dealing with 100K data points you can barely resize the window and the Chart setup/creation is noticeable enough. Dealing with 500K data points is out of the question, the app is pretty much not useable. So I'm wondering if anybody else had a similar issue and what can be done? Is there any "magic" Swift Charts setting that could improve the performance? I have a "data decimation" algorithm, and given no choice I will use it, but somehow I was hoping for Swift Charts to gracefully handle at least 100K data points (there are other libs which do this!). Also, limiting the displayed data range is out of the question for my case, this is a crucial feature of the app. Here's the code that I'm using, but it's the most basic one: struct DataPoint: Identifiable { var id: Double { Double(xValue) } let xValue: Int let yValue: Double } let dataPoints: [DataPoint] = (0..<100_000).map { DataPoint(xValue: $0, yValue: Double($0)) } struct MyChart: View { var body: some View { Chart(dataPoints) { dataPoint in PointMark(x: .value("Index", dataPoint.xValue), y: .value("Y Value", dataPoint.yValue)) } } } Some additional info, if it helps: The Chart is included in a AppKit window via NSHostingController (in my sample project the window contains nothing but the chart) The computer is a MacBook Pro, 2019 and is running macOS 10.14
4
2
2.1k
Sep ’24
Swift Charts Crashing Xcode 16.1 Beta
Feedback FB14988865 Looks like in the latest version of Xcode 16.1 SwiftCharts crashes on launch. Below are the crashlogs. dyld[88826]: Symbol not found: _$s6Charts12BuilderTupleVyxxQp_QPGAA8AxisMarkAARvzAaERzlMc Referenced from: <01BB785A-84AF-3689-A614-DBFEB6A9733F> /Users/xxxx/Library/Developer/CoreSimulator/Devices/A6841249-F73B-45F2-AB68-96F94D75ACF7/data/Containers/Bundle/Application/E88B6681-E933-48AC-920A-150106F12A1F/xxxxx/xxxxx.debug.dylib Expected in: <35624EEC-5BA2-3545-B05D-BABFE6661F1B> /Library/Developer/CoreSimulator/Volumes/iOS_22A5326g/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Charts.framework/Charts It looks related to using AxisMarks to create custom axis.
1
1
745
Sep ’24
Swift Charts 'Pink' chart drawing issue?
On occasion, Swift Charts draws a large pink rectangle over the entire chart area as shown in the screen shot below. I have never been able to reproduce this issue consistently, so I do not know if it is an issue with the data I input into the chart, or an Apple bug. It happens only rarely, for one redraw cycle, then the chart returns to the correct display. Has anyone experienced this issue, and if so, what was the source of the problem and how did you resolve it?
1
1
636
Aug ’24
Swift Charts Accessibility Grouping
SwiftUI Charts automatically groups accessibility elements on the graph (Double / Date for example) when there's a lot of data, which overrides the accessibilityLabel and value I set for each data point. This makes sense, but how do we modify the chart navigation accessibility readout when this grouping occurs? Here's an example: var body: some View { let salesData: [(Date, Double)] = [ (Date().addingTimeInterval(-1 * 24 * 60 * 60), 1200), (Date().addingTimeInterval(-2 * 24 * 60 * 60), 1500), (Date().addingTimeInterval(-3 * 24 * 60 * 60), 1000), (Date().addingTimeInterval(-4 * 24 * 60 * 60), 500), (Date().addingTimeInterval(-5 * 24 * 60 * 60), 1500), (Date().addingTimeInterval(-6 * 24 * 60 * 60), 1400), (Date().addingTimeInterval(-7 * 24 * 60 * 60), 1300), (Date().addingTimeInterval(-8 * 24 * 60 * 60), 1800), (Date().addingTimeInterval(-9 * 24 * 60 * 60), 500), (Date().addingTimeInterval(-10 * 24 * 60 * 60), 800), (Date().addingTimeInterval(-11 * 24 * 60 * 60), 800), (Date().addingTimeInterval(-12 * 24 * 60 * 60), 1000), (Date().addingTimeInterval(-13 * 24 * 60 * 60), 1500), (Date().addingTimeInterval(-14 * 24 * 60 * 60), 1500), (Date().addingTimeInterval(-15 * 24 * 60 * 60), 900), ] Chart { ForEach(salesData, id: \.0) { date, sales in LineMark( x: .value("Foo", date), y: .value("Bar", sales) ).accessibilityLabel("Foo: \(date.formatted(date: .abbreviated, time: .omitted)) Bar: \(sales.formatted(.currency(code: "USD")))") } } .accessibilityElement(children: .contain) } } I am wondering if there's a protocol, modifier.. or maybe something like UIAccessibilityContainerType.
2
3
959
Aug ’24
SwiftUI Chart SectorMark Flips Pie Selection On User Input???
Confused as to why the Chart flips with each user input. The console is also output unique id for each slice which was not my intention. Not sure if the unique .id is the culprit behind the flip. selectedCount changed to: Optional(3) Selected slice: Optional(App.EmojiUsage(id: 69090646-0D0A-4FE8-86EC-4103608DC3F7, emojiTab: App.emojiTab.sad, count: 1)) Scheduling reset task to run in 2 seconds Resetting selected slice and count selectedCount changed to: Optional(1) Selected slice: Optional(App.EmojiUsage(id: DE4A76D1-CC57-4FA0-A261-9AD1A6E28F95, emojiTab: App.emojiTab.happy, count: 2)) Scheduling reset task to run in 2 seconds Resetting selected slice and count selectedCount changed to: Optional(3) Selected slice: Optional(App.EmojiUsage(id: 5052F8EA-2582-4E72-A61D-01FCCDF3DB03, emojiTab: App.emojiTab.sad, count: 1)) Scheduling reset task to run in 2 seconds Resetting selected slice and count selectedCount changed to: Optional(0) Selected slice: Optional(App.EmojiUsage(id: 5C1AB577-6CFC-4BA8-A9DF-30822EF79B91, emojiTab: App.emojiTab.happy, count: 2)) Scheduling reset task to run in 2 seconds @Model class AppModel { var id: String var journalEntry: String var date: Date var emojiTab: emojiTab init(journalEntry: String, date: Date, emojiTab: emojiTab) { self.id = UUID().uuidString self.journalEntry = journalEntry self.date = date self.emojiTab = emojiTab } } struct EmojiPrompt: Identifiable { var id = UUID() var icon: RiveViewModel var emojitab: emojiTab var title: String } enum emojiTab: String, Codable, Plottable { case happy case sad case sleep var primitivePlottable: Double { switch self { case .sleep: return 0.0 case .happy: return 1.0 case .sad: return 2.0 } } } var emojiPrompt = [ EmojiPrompt( icon: RiveViewModel( fileName: "app", stateMachineName: "happyBtnSM", artboardName: "happyBtn" ), emojitab: .happy, title: "Happy 1" ), EmojiPrompt( icon: RiveViewModel( fileName: "app", stateMachineName: "sadBtnSM", artboardName: "sadBtn" ), emojitab: .sad, title: "Sad 2" ), EmojiPrompt( icon: RiveViewModel( fileName: "app", stateMachineName: "happyBtnSM", artboardName: "happyBtn" ), emojitab: .sleep, title: "Sleep" ) ] import SwiftUI import SwiftData import RiveRuntime import Charts struct SectorChartView: View { @Environment(\.modelContext) private var context: ModelContext @Binding var selectedEmojiUsage: EmojiUsage? @State private var selectedCount: Int? @Binding var selectedSlice: EmojiUsage? @State private var resetTask: DispatchWorkItem? // State variable for the reset task var emojiUsageData: [EmojiUsage] var resetDelay: TimeInterval = 2.0 // Adjustable delay for reset var body: some View { ZStack { Chart { ForEach(emojiUsageData) { data in SectorMark( angle: .value("Count", data.count), innerRadius: .ratio(0.70), outerRadius: selectedSlice?.emojiTab == data.emojiTab ? .ratio(1.0) : .ratio(0.75), angularInset: 1.5 ) .cornerRadius(4) .foregroundStyle(by: .value("Emoji", data.emojiTab.rawValue.capitalized)) } } .chartAngleSelection(value: $selectedCount) .chartBackground { chartProxy in GeometryReader { geo in let frame = geo[chartProxy.plotFrame!] VStack { if let selectedEmojiUsage = selectedEmojiUsage { RiveViewModel(fileName: "app", stateMachineName: "\(selectedEmojiUsage.emojiTab.rawValue)BtnSM", artboardName: "\(selectedEmojiUsage.emojiTab.rawValue)Btn") .view() .frame(width: 120, height: 120) .id(selectedEmojiUsage.emojiTab.rawValue) // Force re-render when the emojiTab changes } else { RiveViewModel(fileName: "app", stateMachineName: "sleepBtnSM", artboardName: "sleepBtn") .view() .frame(width: 120, height: 120) .id("sleep") // Force re-render when default state } } .position(x: frame.midX, y: frame.midY) } } } .onChange(of: selectedCount) { oldValue, newValue in // Ensure reset task is only scheduled if there is a valid new value guard newValue != nil else { return } resetTask?.cancel() // Cancel any existing reset task print("selectedCount changed to: \(String(describing: newValue))") if let newValue = newValue { withAnimation { getSelectedSlice(value: newValue) } let task = DispatchWorkItem { withAnimation(.easeIn) { print("Resetting selected slice and count") self.selectedSlice = nil self.selectedCount = nil self.selectedEmojiUsage = nil } } resetTask = task print("Scheduling reset task to run in 2 seconds") DispatchQueue.main.asyncAfter(deadline: .now() + resetDelay, execute: task) // Schedule reset after specified delay } } .frame(width: 250, height: 250) } private func getSelectedSlice(value: Int) { var cumulativeTotal = 0 _ = emojiUsageData.first { emojiRange in cumulativeTotal += emojiRange.count if value <= cumulativeTotal { selectedSlice = emojiRange selectedEmojiUsage = emojiRange print("Selected slice: \(String(describing: selectedSlice))") return true } return false } } } var emojiUsageData: [EmojiUsage] { let groupedEntries = Dictionary(grouping: entries, by: { $0.emojiTab }) return groupedEntries.map { (key, value) in EmojiUsage(emojiTab: key, count: value.count) } } struct EmojiUsage: Identifiable { var id = UUID() var emojiTab: emojiTab var count: Int }
3
0
1k
Aug ’24
How do you skip 0 values on x axis in a SwiftUI Chart
I am plotting a SwiftUI chart from a Struct that looks like this: struct BestWeights: Identifiable { let id = UUID() let date: String let maxWeight: Int } I am then creating an array of this Struct that I will use to plot the Chart: private var bestWeights: [BestWeights] { let unformattedMonth = DateFormatter().monthSymbols[month - 1] let formattedMonth = String(unformattedMonth.prefix(3)) bestWeights.append(BestWeights(date: formattedMonth, maxWeight: bestWeightOfPeriod)) //decrementing down one month selectedDate = Calendar.current.date(byAdding: .month, value: -1, to: selectedDate) ?? selectedDate Then I am iterating through bestWeights and plotting them: Chart { ForEach(bestWeights) { bestWeight in LineMark(x: .value("Date",bestWeight.date), y: .value("MaxWeight", bestWeight.maxWeight)) .symbol { Circle() .fill(.blue) .frame(width: 7, height: 7) } } } The problem is that this produces 0 values on the Y axis that scrape the bottom of the LineMark, now I can fix this by not adding all of the bestWeights who's weight is 0 but then I don't get the full x axis I want which is 6 full months, it would show only the number of months as we have records and would jump from February to July etc.. is there any way to remove the 0 weights while keeping the X axis full of dates
1
0
719
Aug ’24
SwiftCharts Not Showing Accurate Data Until Tap Gesture on Chart
I am showing weather data in a TabView where each tab will show the forecast for that day and then an hour-by-hour Swift Charts of the temperature, chance of precipitation, and then dew point for that day. The day and a text description of that forecast correctly displays for each tab. However, the chart will only show the correct data if you perform a tap gesture on the chart. To reproduce this issue, I do the following: Tap on a day in the "Upcoming Week", preferably a day in the middle. Swipe a couple days to the left or right and use the tap gesture on one of the charts. Oddly, other data on the tab is accurate, it is really just within the SwiftChart. I did try doing a horizontal ScrollView instead but I had the same issue. I also followed the demo for SwiftCharts from WWDC. Below is code that shows the TabView: struct UpcomingDaysView: View { let forecastModel:WeatherModel @State var targetPeriod:WeatherForecastDayPeriod var body: some View { TabView(selection:$targetPeriod) { ForEach(forecastModel.dailyPeriods, id: \.self) {period in DailyViewChartDetail(forecastModel: forecastModel, periodToShow: period) .frame(alignment: .topLeading) .tag(period) } } .containerRelativeFrame([.vertical]) .tabViewStyle(.page) .indexViewStyle(.page(backgroundDisplayMode: .always)) .padding(EdgeInsets(top: 20, leading: 0, bottom: 0, trailing: 0)) } } } And here is the DailyViewChartDetail: struct DailyViewChartDetail: View { var forecastModel:WeatherModel var periodToShow:WeatherForecastDayPeriod var body: some View { VStack { Text("\(DateUtility.getLongerDay(date: DateUtility.getDate(stringDate: periodToShow.dayForecast.startTime)))") .font(.title2) Text("\(periodToShow.dayForecast.detailedForecast)") .font(.subheadline) .padding(5) HourlyViewChart(forecastModel: WeatherPeriodUtility.filterModel(forecastModel: forecastModel, targetPeriod: periodToShow)) .padding(5) Spacer() } .frame( alignment: .topLeading ) } } And then some of the more relevant code in the HourlyViewChart struct HourlyViewChart: View { var forecastModel:WeatherModel @State var range: (Date, Date)? = nil @State var rawSelectedDateTemp: Date? = nil @State var rawSelectedDatePrecipitation: Date? = nil @State var rawSelectedDewPoint: Date? = nil // ... more code Below is an image that shows the issue:
2
0
908
Aug ’24
How to show scroll bars on a Swift Chart for macOS?
(I'm using macOS 14.5 and Xcode 15.4) I have a Swift Chart on macOS that needs to scroll horizontally. Simplified version: Chart(dataPoints) { data in LineMark(x: .value("X Axis", data.x), y: .value("Y Axis", data.y)) } .chartScrollableAxes(.horizontal) .chartXVisibleDomain(length: 10) The above code works fine, except that it does not show scroll bars. On a Mac with no trackpad, this means there's no mechanism to scroll the chart. On my MacBook Pro with a trackpad, I can scroll the chart with a 2-finger swipe gesture, but there are no transient scroll bars to show the relative size of the visible part of the chart. How do I add visible scroll bars to the chart so that I can scroll on Macs with no trackpad?
0
0
599
Jul ’24
Swift Charts: Changing chartXVisibleDomain changes chartScrollPosition
I'm building a Swift Chart that displays locations in a horizontal timeline. The chart is scrollable. Unfortunately, when chartScrollPosition is offset by some amount (i.e. the user has scrolled the chart), changing chartXVisibleDomain results in chartScrollPosition jumping backwards by some amount. This results in bad user experience. A minimum reproducible example is below. To reproduce: Run the code below Using the picker, change chartXVisibleDomain. ThechartScrollPosition remains the same, as expected. Scroll the chart on the horizontal axis. Using the picker, change chartXVisibleDomain. ThechartScrollPosition changes unexpectedly. You can verify this by watching the labels at the bottom of the chart. The chart simply ends up showing a different area of the domain. Tested on various iPhone and iPad simulators and physical devices, the issue appears everywhere. Is this a SwiftUI bug, or am I doing something wrong? struct ScrollableChartBug: View { /// Sample data let data = SampleData.samples let startDate = SampleData.samples.first?.startDate ?? Date() let endDate = Date() /// Scroll position of the chart, expressed as Date along the x-axis. @State var chartPosition: Date = SampleData.samples.first?.startDate ?? Date() /// Sets the granularity of the shown view. @State var visibleDomain: VisibleDomain = .year var body: some View { Chart(data, id: \.id) { element in BarMark(xStart: .value("Start", element.startDate), xEnd: .value("End", element.endDate), yStart: 0, yEnd: 50) .foregroundStyle(by: .value("Type", element.type.rawValue)) .clipShape(.rect(cornerRadius: 8, style: .continuous)) } .chartScrollableAxes(.horizontal) // enable scroll .chartScrollPosition(x: $chartPosition) // track scroll offset .chartXVisibleDomain(length: visibleDomain.seconds) .chartXScale(domain: startDate...endDate) .chartForegroundStyleScale { typeName in // custom colors for bars and for legend SampleDataType(rawValue: typeName)?.color ?? .clear } .chartXAxis { AxisMarks(values: .stride(by: .month, count: 1)) { value in if let date = value.as(Date.self) { AxisValueLabel { Text(date, format: .dateTime.year().month().day()) .bold() } AxisTick(length: .label) } } } .frame(height: 90) .padding(.bottom, 40) // for overlay picker .overlay { Picker("", selection: $visibleDomain.animation()) { ForEach(VisibleDomain.allCases) { variant in Text(variant.label) .tag(variant) } } .pickerStyle(.segmented) .frame(width: 240) .padding(.trailing) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing) } //: overlay } //: body } //: struct // MARK: - Preview #Preview { ScrollableChartBug() } // MARK: - Data enum SampleDataType: String, CaseIterable { case city, wood, field var color: Color { switch self { case .city: .gray case .wood: .green case .field: .brown } } var label: String { switch self { case .city: "City" case .wood: "Wood" case .field: "Field" } } } enum VisibleDomain: Identifiable, CaseIterable { case day case week case month case year var id: Int { self.seconds } var seconds: Int { switch self { case .day: 3600 * 24 * 2 case .week: 3600 * 24 * 10 case .month: 3600 * 24 * 40 case .year: 3600 * 24 * 400 } } var label: String { switch self { case .day: "Days" case .week: "Weeks" case .month: "Months" case .year: "Years" } } } struct SampleData: Identifiable { let startDate: Date let endDate: Date let name: String let type: SampleDataType var id: String { name } static let samples: [SampleData] = [ .init(startDate: Date.from(year: 2022, month: 3, day: 1), endDate: Date.from(year: 2022, month: 3, day: 10), name: "New York", type: .city), .init(startDate: Date.from(year: 2022, month: 3, day: 20, hour: 6), endDate: Date.from(year: 2022, month: 5, day: 1), name: "London", type: .city), .init(startDate: Date.from(year: 2022, month: 5, day: 4), endDate: Date.from(year: 2022, month: 7, day: 5), name: "Backcountry ABC", type: .field), .init(startDate: Date.from(year: 2022, month: 7, day: 5), endDate: Date.from(year: 2022, month: 10, day: 10), name: "Field DEF", type: .field), .init(startDate: Date.from(year: 2022, month: 10, day: 10), endDate: Date.from(year: 2023, month: 2, day: 10), name: "Wood 123", type: .wood), .init(startDate: Date.from(year: 2023, month: 2, day: 10), endDate: Date.from(year: 2023, month: 3, day: 20), name: "Paris", type: .city), .init(startDate: Date.from(year: 2023, month: 3, day: 21), endDate: Date.from(year: 2023, month: 10, day: 5), name: "Field GHI", type: .field), .init(startDate: Date.from(year: 2023, month: 10, day: 5), endDate: Date.from(year: 2024, month: 3, day: 5), name: "Wood 456", type: .wood), .init(startDate: Date.from(year: 2024, month: 3, day: 6), endDate: Date(), name: "Field JKL", type: .field) ] } extension Date { /** Constructs a Date from a given year (Int). Use like `Date.from(year: 2020)`. */ static func from(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil) -> Date { let components = DateComponents(year: year, month: month, day: day, hour: hour, minute: minute) guard let date = Calendar.current.date(from: components) else { print(#function, "Failed to construct date. Returning current date.") return Date() } return date } }
3
2
1.8k
Jul ’24
Swift Charts: .hour annotations do not appear
I'm building a Swift Chart that displays locations in a horizontal timeline. The chart is scrollable. When the chart is zoomed in, I want to show an annotation for every 6 hours. Unfortunately, when axisMarks are set to .stride(by: .hour, count: 6), the annotations do not appear for the first several months in the timeline. I tried setting .stride(by: .minute, count: 360), but the result is the same. Is this a Swift Charts bug, or am I doing something wrong? A reproducible example is below. To reproduce: Run the code below See that annotations are missing at the leading edge of the chart. They only show up from a certain point on the chart's domain. Tested on various iPhone and iPad simulators and physical devices, the issue appears everywhere. P.S. I am aware that the example code below is not performant and that the annotations overlap when the chart is zoomed out. I have workarounds for that, but it's beyond the scope of my question and the minimum reproducible example. struct ChartAnnotationsBug: View { /// Sample data let data = SampleData.samples let startDate = SampleData.samples.first?.startDate ?? Date() let endDate = Date() /// Scroll position of the chart, expressed as Date along the x-axis. @State var chartPosition: Date = SampleData.samples.first?.startDate ?? Date() /// Sets the granularity of the shown view. @State var visibleDomain: VisibleDomain = .month var body: some View { Chart(data, id: \.id) { element in BarMark(xStart: .value("Start", element.startDate), xEnd: .value("End", element.endDate), yStart: 0, yEnd: 50) .foregroundStyle(by: .value("Type", element.type.rawValue)) .clipShape(.rect(cornerRadius: 8, style: .continuous)) } .chartScrollableAxes(.horizontal) // enable scroll .chartScrollPosition(x: $chartPosition) // track scroll offset .chartXVisibleDomain(length: visibleDomain.seconds) .chartXScale(domain: startDate...endDate) .chartXAxis { AxisMarks(values: .stride(by: .hour, count: 6)) { value in if let date = value.as(Date.self) { let hour = Calendar.current.component(.hour, from: date) if hour == 0 { // midnight AxisValueLabel(collisionResolution: .truncate) { VStack(alignment: .leading) { Text(date, format: .dateTime.hour().minute()) Text(date, format: .dateTime.weekday().month().day()) .bold() } } AxisTick(stroke: .init(lineWidth: 1)) } else if [6, 12, 18].contains(hour) { // period AxisValueLabel(collisionResolution: .truncate) { Text(date, format: .dateTime.hour().minute()) } AxisTick(length: .label) } } } } .frame(height: 100) .padding(.bottom, 40) // for overlay picker .overlay { Picker("", selection: $visibleDomain.animation()) { ForEach(VisibleDomain.allCases) { variant in Text(variant.label) .tag(variant) } } .pickerStyle(.segmented) .frame(width: 240) .padding(.trailing) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing) } //: overlay } //: body } //: struct // MARK: - Preview #Preview { ChartAnnotationsBug() } // MARK: - Data enum SampleDataType: String, CaseIterable { case city, wood, field var label: String { switch self { case .city: "City" case .wood: "Wood" case .field: "Field" } } } enum VisibleDomain: Identifiable, CaseIterable { case day case week case month var id: Int { self.seconds } var seconds: Int { switch self { case .day: 3600 * 24 * 2 case .week: 3600 * 24 * 10 case .month: 3600 * 24 * 40 } } var label: String { switch self { case .day: "Days" case .week: "Weeks" case .month: "Months" } } } struct SampleData: Identifiable { let startDate: Date let endDate: Date let name: String let type: SampleDataType var id: String { name } static let samples: [SampleData] = [ .init(startDate: Date.from(year: 2024, month: 3, day: 1, hour: 23, minute: 59), endDate: Date.from(year: 2024, month: 3, day: 10), name: "New York", type: .city), .init(startDate: Date.from(year: 2024, month: 3, day: 10, hour: 6), endDate: Date.from(year: 2024, month: 3, day: 20), name: "London", type: .city), .init(startDate: Date.from(year: 2024, month: 3, day: 20), endDate: Date.from(year: 2024, month: 4, day: 10), name: "Backcountry ABC", type: .field), .init(startDate: Date.from(year: 2024, month: 4, day: 10), endDate: Date.from(year: 2024, month: 4, day: 20), name: "Field DEF", type: .field), .init(startDate: Date.from(year: 2024, month: 4, day: 20), endDate: Date.from(year: 2024, month: 5, day: 10), name: "Wood 123", type: .wood), .init(startDate: Date.from(year: 2024, month: 5, day: 10), endDate: Date.from(year: 2024, month: 5, day: 20), name: "Paris", type: .city), .init(startDate: Date.from(year: 2024, month: 5, day: 20), endDate: Date.from(year: 2024, month: 6, day: 5), name: "Field GHI", type: .field), .init(startDate: Date.from(year: 2024, month: 6, day: 5), endDate: Date.from(year: 2024, month: 6, day: 10), name: "Wood 456", type: .wood), .init(startDate: Date.from(year: 2024, month: 6, day: 10), endDate: Date(), name: "Field JKL", type: .field) ] } extension Date { /** Constructs a Date from a given year (Int). Use like `Date.from(year: 2020)`. */ static func from(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil) -> Date { let components = DateComponents(year: year, month: month, day: day, hour: hour, minute: minute) guard let date = Calendar.current.date(from: components) else { print(#function, "Failed to construct date. Returning current date.") return Date() } return date } }
3
2
1.3k
Jul ’24
SwiftUI charts, how do I align these X axis labels correctly?
Hi there, so I have this chart that's taking in a Date for it's x values and a time interval for their y values. For some reason, the labels aren't centering on each bar, the only fix I see is to add an offset to each label but that seems hacky. My code: Chart { ForEach(weekBreakdownArr, id: \.startDate) { bd in BarMark( x: .value("Date", bd.startDate), y: .value("Duration", bd.durationWorkDone), width: .fixed(15) ) .foregroundStyle(Color.redYarn) .cornerRadius(2) } //... } // shownXValues are just the start dates in an array .chartXAxis { AxisMarks(position: .automatic, values: shownXValues) { val in AxisValueLabel { Text("Th") .useAppFont(size: 12, relativeTo: .body, weight: .regular) } } }
Replies
1
Boosts
0
Views
771
Activity
Dec ’24
Swift Charts legend overflowing outside frame
I'm building an app that lets users create charts with custom values and while testing, I came up with this bug that happens when the view width forces the legend to have more than 1 line. Due to Swift trying to align the different labels vertically, it's forcing the first line to overflow. Here's the code to generate this: import SwiftUI import Charts struct DonutView: View { var countries:[(country:String, count:Int)] = [ (country: "Africa", count: 54), (country: "Asia", count: 48), (country: "Europe", count: 44), (country: "North America", count: 23), (country: "Oceania", count: 14), (country: "South America", count: 12), ] var body: some View { Chart { ForEach(0..<countries.count, id:\.self) { idx in SectorMark( angle: .value(countries[idx].country, countries[idx].count), innerRadius: .ratio(0.5) ) .foregroundStyle(by: .value("label", countries[idx].country)) } } .frame(width: 310, height: 270) .border(.blue, width: 1) } } Has anyone seen this? Is there a solution? I know about building custom legends, but SwiftUI has no wrapping HStack nor VStack, and the app allows users to change the legend position from the bottom to the top or sides. If I were to go this way, I'd have to write a very large chunk of code to bypass what seems to be a bug.
Replies
1
Boosts
0
Views
597
Activity
Dec ’24
Swift Charts: chartScrollTargetBehavior fails to snap to a day unit
I am working on a scrollable chart that displays days on the horizontal axis. As the user scrolls, I always want them to be able to snap to a specific day. I implemented the following steps described in this WWDC23 session to achieve this. I have set the chartScrollTargetBehavior to .valueAligned(matching: DateComponents(hour: 0)) I have set the x value unit on the BarMark to Calendar.Component.day I ended up with the chart code that looks like this: Chart(dates, id: \.self) { date in BarMark( x: .value("Date", date, unit: Calendar.Component.day), y: .value("Number", 1) ) .annotation { Text(date.formatted(.dateTime.day())) .font(.caption2) } } .chartXAxis { AxisMarks(format: .dateTime.day()) } .chartScrollableAxes(.horizontal) .chartScrollTargetBehavior(.valueAligned(matching: DateComponents(hour: 0))) .chartXVisibleDomain(length: fifteenDays) .chartScrollPosition(x: $selection) However, this fails to work reliably. There is often a situation where the chart scroll position lands on, for instance, Oct 20, 11:56 PM, but the chart snaps to Oct 21. I attempted to solve this problem by introducing an intermediate binding between a state value and a chart selection. This binding aims to normalize the selection always to be the first moment of any given date. But this hasn't been successful. private var selectionBinding: Binding<Date> { Binding { Calendar.current.startOfDay(for: selection) } set: { newValue in self.selection = Calendar.current.startOfDay(for: newValue) } } It's also worth mentioning that this issue also exists in Apple's sample project on Swift Charts. How would you approach solving this? How can I find a way to make the chart scroll position blind to time values and only recognize whole days? Here's the minimal reproducible example project for your reference.
Replies
1
Boosts
1
Views
677
Activity
Nov ’24
Swift UI Chart Accessibility issue
Hi Team, We are integrating SwiftUI's Charts BarMark, UI looks good but when we try setting up custom ADA it doesn't reflect/override the accessibility label/value we set manually. Is it iOS defect or is there any workaround? Thanks in advance. Sample: Chart(data) { BarMark( x: .value("Category", $0.department), y: .value("Profit", $0.profit) ) .foregroundStyle(by: .value("Product Category", $0.productCategory)) .accessibilityIdentifier("BarMark") .accessibilityLabel("Dep: \($0.department)") .accessibilityValue("Profile: \($0.profit) Category: \($0.productCategory)") }
Replies
1
Boosts
2
Views
688
Activity
Nov ’24
Tranforming a chart's origin
Hi, I'm trying to create a visualization using charts for vision pro. I want to create a line chart that connects pair of points on a donut chart. So i'm trying to draw the lines radially but it seems that the line chart always has only the bottom left corner of the view as origin. How can I tranform the origin to center of the view?
Topic: Design SubTopic: General Tags:
Replies
1
Boosts
0
Views
714
Activity
Oct ’24
SwiftUI Charts not working in Xcode 16 Beta 2
Is there a way to workaround this issue? Can I revert back to Beta 1? Failed to build module 'Charts'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.7.41 clang-1600.0.24.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.11 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK.
Replies
2
Boosts
1
Views
1.1k
Activity
Oct ’24
Unable to compile SwiftUI Charts on Xcode 16.1 Beta 2
Unable to compile app that imports Swift UI Charts SDK on Xcode Version 16.1 beta 2 (16B5014f) with error: Failed to build module 'Charts'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.7.41 clang-1600.0.24.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.11 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK. FB15161667
Replies
5
Boosts
15
Views
2.5k
Activity
Oct ’24
Unable to import Charts in Xcode 16.1 beta 2
Failed to build module 'Charts'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.7.41 clang-1600.0.24.1)', while this compiler is 'Apple Swift version 6.0 effective-5.10 (swiftlang-6.0.0.9.11 clang-1600.0.26.2)'). Please select a toolchain which matches the SDK. Any fix yet?
Replies
2
Boosts
2
Views
833
Activity
Oct ’24
SwiftUI charts scroll feature is not working with iOS v18.0
Using just basic rule .chartScrollableAxes(.horizontal) .chartXVisibleDomain(length: 6) Feature is working fine for iOS 17.x devices
Replies
0
Boosts
1
Views
520
Activity
Sep ’24
VoiceOver ignoring a data series when there are multiple ones
I can't figure out if I've found a VoiceOver problem with Swift Charts or if I'm doing something incorrectly. I have a loop within a loop showing 2 sets of data in the same chart. If I touch a month then VO correctly says there are two data series. But if I keep swiping down only data from the first series is read. ChatGPT said try referencing the outer loop and sure enough that worked if it done in BOTH the label and value. It sounds really awkward though. For example, "High 89 degrees F High October". Below the "bad" chart only says something such as "92 degrees F October" when swiping down. The "good" chart will read the high and low temperature data. VStack { headerText("BAD") Chart { ForEach(processedMonthlyInput) { oneMonth in ForEach(oneMonth.temperatures, id: \.month) { element in LineMark( x: .value("Month", element.month, unit: .month), y: .value("Temperature", element.tempVal.converted(to: .fahrenheit).value) ) .accessibilityLabel("\(element.month.formatted(.dateTime.month(.wide)))") .accessibilityValue(Text("\(element.tempVal.converted(to: tempUnit).formatted(.measurement(width: .abbreviated, numberFormatStyle: .number.precision(.fractionLength(0)))))")) } .symbol(by: .value("Type", oneMonth.theType)) .foregroundStyle(by: .value("Type", oneMonth.theType)) .interpolationMethod(.catmullRom) } } .frame(maxHeight: paddingAmount) .padding(.horizontal) headerText("GOOD") Chart { ForEach(processedMonthlyInput) { oneMonth in ForEach(oneMonth.temperatures, id: \.month) { element in LineMark( x: .value("Month", element.month, unit: .month), y: .value("Temperature", element.tempVal.converted(to: .fahrenheit).value) ) .accessibilityLabel("\(oneMonth.theType) \(element.month.formatted(.dateTime.month(.wide)))") .accessibilityValue(Text("\(oneMonth.theType) \(element.tempVal.converted(to: tempUnit).formatted(.measurement(width: .abbreviated, numberFormatStyle: .number.precision(.fractionLength(0)))))")) } .symbol(by: .value("Type", oneMonth.theType)) .foregroundStyle(by: .value("Type", oneMonth.theType)) .interpolationMethod(.catmullRom) } } .frame(maxHeight: paddingAmount) .padding(.horizontal) }
Replies
0
Boosts
0
Views
590
Activity
Sep ’24
Swift Charts performance when displaying many data points
I'm currently evaluating Swift Charts to use in my macOS app, where I need to (potentially) display a few millions of data points, ideally all of them at one time. I want to give users the possibility to zoom in & out, so the entire range of values could be displayed at one moment. However, starting at around 20K data points (on my computer), the Chart takes a little bit to set up, but the window resizing is laggy. The performance seems to decrease linearly (?), when dealing with 100K data points you can barely resize the window and the Chart setup/creation is noticeable enough. Dealing with 500K data points is out of the question, the app is pretty much not useable. So I'm wondering if anybody else had a similar issue and what can be done? Is there any "magic" Swift Charts setting that could improve the performance? I have a "data decimation" algorithm, and given no choice I will use it, but somehow I was hoping for Swift Charts to gracefully handle at least 100K data points (there are other libs which do this!). Also, limiting the displayed data range is out of the question for my case, this is a crucial feature of the app. Here's the code that I'm using, but it's the most basic one: struct DataPoint: Identifiable { var id: Double { Double(xValue) } let xValue: Int let yValue: Double } let dataPoints: [DataPoint] = (0..<100_000).map { DataPoint(xValue: $0, yValue: Double($0)) } struct MyChart: View { var body: some View { Chart(dataPoints) { dataPoint in PointMark(x: .value("Index", dataPoint.xValue), y: .value("Y Value", dataPoint.yValue)) } } } Some additional info, if it helps: The Chart is included in a AppKit window via NSHostingController (in my sample project the window contains nothing but the chart) The computer is a MacBook Pro, 2019 and is running macOS 10.14
Replies
4
Boosts
2
Views
2.1k
Activity
Sep ’24
Swift Charts Crashing Xcode 16.1 Beta
Feedback FB14988865 Looks like in the latest version of Xcode 16.1 SwiftCharts crashes on launch. Below are the crashlogs. dyld[88826]: Symbol not found: _$s6Charts12BuilderTupleVyxxQp_QPGAA8AxisMarkAARvzAaERzlMc Referenced from: <01BB785A-84AF-3689-A614-DBFEB6A9733F> /Users/xxxx/Library/Developer/CoreSimulator/Devices/A6841249-F73B-45F2-AB68-96F94D75ACF7/data/Containers/Bundle/Application/E88B6681-E933-48AC-920A-150106F12A1F/xxxxx/xxxxx.debug.dylib Expected in: <35624EEC-5BA2-3545-B05D-BABFE6661F1B> /Library/Developer/CoreSimulator/Volumes/iOS_22A5326g/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Charts.framework/Charts It looks related to using AxisMarks to create custom axis.
Replies
1
Boosts
1
Views
745
Activity
Sep ’24
Swift Charts 'Pink' chart drawing issue?
On occasion, Swift Charts draws a large pink rectangle over the entire chart area as shown in the screen shot below. I have never been able to reproduce this issue consistently, so I do not know if it is an issue with the data I input into the chart, or an Apple bug. It happens only rarely, for one redraw cycle, then the chart returns to the correct display. Has anyone experienced this issue, and if so, what was the source of the problem and how did you resolve it?
Replies
1
Boosts
1
Views
636
Activity
Aug ’24
Swift Charts Accessibility Grouping
SwiftUI Charts automatically groups accessibility elements on the graph (Double / Date for example) when there's a lot of data, which overrides the accessibilityLabel and value I set for each data point. This makes sense, but how do we modify the chart navigation accessibility readout when this grouping occurs? Here's an example: var body: some View { let salesData: [(Date, Double)] = [ (Date().addingTimeInterval(-1 * 24 * 60 * 60), 1200), (Date().addingTimeInterval(-2 * 24 * 60 * 60), 1500), (Date().addingTimeInterval(-3 * 24 * 60 * 60), 1000), (Date().addingTimeInterval(-4 * 24 * 60 * 60), 500), (Date().addingTimeInterval(-5 * 24 * 60 * 60), 1500), (Date().addingTimeInterval(-6 * 24 * 60 * 60), 1400), (Date().addingTimeInterval(-7 * 24 * 60 * 60), 1300), (Date().addingTimeInterval(-8 * 24 * 60 * 60), 1800), (Date().addingTimeInterval(-9 * 24 * 60 * 60), 500), (Date().addingTimeInterval(-10 * 24 * 60 * 60), 800), (Date().addingTimeInterval(-11 * 24 * 60 * 60), 800), (Date().addingTimeInterval(-12 * 24 * 60 * 60), 1000), (Date().addingTimeInterval(-13 * 24 * 60 * 60), 1500), (Date().addingTimeInterval(-14 * 24 * 60 * 60), 1500), (Date().addingTimeInterval(-15 * 24 * 60 * 60), 900), ] Chart { ForEach(salesData, id: \.0) { date, sales in LineMark( x: .value("Foo", date), y: .value("Bar", sales) ).accessibilityLabel("Foo: \(date.formatted(date: .abbreviated, time: .omitted)) Bar: \(sales.formatted(.currency(code: "USD")))") } } .accessibilityElement(children: .contain) } } I am wondering if there's a protocol, modifier.. or maybe something like UIAccessibilityContainerType.
Replies
2
Boosts
3
Views
959
Activity
Aug ’24
SwiftUI Chart SectorMark Flips Pie Selection On User Input???
Confused as to why the Chart flips with each user input. The console is also output unique id for each slice which was not my intention. Not sure if the unique .id is the culprit behind the flip. selectedCount changed to: Optional(3) Selected slice: Optional(App.EmojiUsage(id: 69090646-0D0A-4FE8-86EC-4103608DC3F7, emojiTab: App.emojiTab.sad, count: 1)) Scheduling reset task to run in 2 seconds Resetting selected slice and count selectedCount changed to: Optional(1) Selected slice: Optional(App.EmojiUsage(id: DE4A76D1-CC57-4FA0-A261-9AD1A6E28F95, emojiTab: App.emojiTab.happy, count: 2)) Scheduling reset task to run in 2 seconds Resetting selected slice and count selectedCount changed to: Optional(3) Selected slice: Optional(App.EmojiUsage(id: 5052F8EA-2582-4E72-A61D-01FCCDF3DB03, emojiTab: App.emojiTab.sad, count: 1)) Scheduling reset task to run in 2 seconds Resetting selected slice and count selectedCount changed to: Optional(0) Selected slice: Optional(App.EmojiUsage(id: 5C1AB577-6CFC-4BA8-A9DF-30822EF79B91, emojiTab: App.emojiTab.happy, count: 2)) Scheduling reset task to run in 2 seconds @Model class AppModel { var id: String var journalEntry: String var date: Date var emojiTab: emojiTab init(journalEntry: String, date: Date, emojiTab: emojiTab) { self.id = UUID().uuidString self.journalEntry = journalEntry self.date = date self.emojiTab = emojiTab } } struct EmojiPrompt: Identifiable { var id = UUID() var icon: RiveViewModel var emojitab: emojiTab var title: String } enum emojiTab: String, Codable, Plottable { case happy case sad case sleep var primitivePlottable: Double { switch self { case .sleep: return 0.0 case .happy: return 1.0 case .sad: return 2.0 } } } var emojiPrompt = [ EmojiPrompt( icon: RiveViewModel( fileName: "app", stateMachineName: "happyBtnSM", artboardName: "happyBtn" ), emojitab: .happy, title: "Happy 1" ), EmojiPrompt( icon: RiveViewModel( fileName: "app", stateMachineName: "sadBtnSM", artboardName: "sadBtn" ), emojitab: .sad, title: "Sad 2" ), EmojiPrompt( icon: RiveViewModel( fileName: "app", stateMachineName: "happyBtnSM", artboardName: "happyBtn" ), emojitab: .sleep, title: "Sleep" ) ] import SwiftUI import SwiftData import RiveRuntime import Charts struct SectorChartView: View { @Environment(\.modelContext) private var context: ModelContext @Binding var selectedEmojiUsage: EmojiUsage? @State private var selectedCount: Int? @Binding var selectedSlice: EmojiUsage? @State private var resetTask: DispatchWorkItem? // State variable for the reset task var emojiUsageData: [EmojiUsage] var resetDelay: TimeInterval = 2.0 // Adjustable delay for reset var body: some View { ZStack { Chart { ForEach(emojiUsageData) { data in SectorMark( angle: .value("Count", data.count), innerRadius: .ratio(0.70), outerRadius: selectedSlice?.emojiTab == data.emojiTab ? .ratio(1.0) : .ratio(0.75), angularInset: 1.5 ) .cornerRadius(4) .foregroundStyle(by: .value("Emoji", data.emojiTab.rawValue.capitalized)) } } .chartAngleSelection(value: $selectedCount) .chartBackground { chartProxy in GeometryReader { geo in let frame = geo[chartProxy.plotFrame!] VStack { if let selectedEmojiUsage = selectedEmojiUsage { RiveViewModel(fileName: "app", stateMachineName: "\(selectedEmojiUsage.emojiTab.rawValue)BtnSM", artboardName: "\(selectedEmojiUsage.emojiTab.rawValue)Btn") .view() .frame(width: 120, height: 120) .id(selectedEmojiUsage.emojiTab.rawValue) // Force re-render when the emojiTab changes } else { RiveViewModel(fileName: "app", stateMachineName: "sleepBtnSM", artboardName: "sleepBtn") .view() .frame(width: 120, height: 120) .id("sleep") // Force re-render when default state } } .position(x: frame.midX, y: frame.midY) } } } .onChange(of: selectedCount) { oldValue, newValue in // Ensure reset task is only scheduled if there is a valid new value guard newValue != nil else { return } resetTask?.cancel() // Cancel any existing reset task print("selectedCount changed to: \(String(describing: newValue))") if let newValue = newValue { withAnimation { getSelectedSlice(value: newValue) } let task = DispatchWorkItem { withAnimation(.easeIn) { print("Resetting selected slice and count") self.selectedSlice = nil self.selectedCount = nil self.selectedEmojiUsage = nil } } resetTask = task print("Scheduling reset task to run in 2 seconds") DispatchQueue.main.asyncAfter(deadline: .now() + resetDelay, execute: task) // Schedule reset after specified delay } } .frame(width: 250, height: 250) } private func getSelectedSlice(value: Int) { var cumulativeTotal = 0 _ = emojiUsageData.first { emojiRange in cumulativeTotal += emojiRange.count if value <= cumulativeTotal { selectedSlice = emojiRange selectedEmojiUsage = emojiRange print("Selected slice: \(String(describing: selectedSlice))") return true } return false } } } var emojiUsageData: [EmojiUsage] { let groupedEntries = Dictionary(grouping: entries, by: { $0.emojiTab }) return groupedEntries.map { (key, value) in EmojiUsage(emojiTab: key, count: value.count) } } struct EmojiUsage: Identifiable { var id = UUID() var emojiTab: emojiTab var count: Int }
Replies
3
Boosts
0
Views
1k
Activity
Aug ’24
How do you skip 0 values on x axis in a SwiftUI Chart
I am plotting a SwiftUI chart from a Struct that looks like this: struct BestWeights: Identifiable { let id = UUID() let date: String let maxWeight: Int } I am then creating an array of this Struct that I will use to plot the Chart: private var bestWeights: [BestWeights] { let unformattedMonth = DateFormatter().monthSymbols[month - 1] let formattedMonth = String(unformattedMonth.prefix(3)) bestWeights.append(BestWeights(date: formattedMonth, maxWeight: bestWeightOfPeriod)) //decrementing down one month selectedDate = Calendar.current.date(byAdding: .month, value: -1, to: selectedDate) ?? selectedDate Then I am iterating through bestWeights and plotting them: Chart { ForEach(bestWeights) { bestWeight in LineMark(x: .value("Date",bestWeight.date), y: .value("MaxWeight", bestWeight.maxWeight)) .symbol { Circle() .fill(.blue) .frame(width: 7, height: 7) } } } The problem is that this produces 0 values on the Y axis that scrape the bottom of the LineMark, now I can fix this by not adding all of the bestWeights who's weight is 0 but then I don't get the full x axis I want which is 6 full months, it would show only the number of months as we have records and would jump from February to July etc.. is there any way to remove the 0 weights while keeping the X axis full of dates
Replies
1
Boosts
0
Views
719
Activity
Aug ’24
SwiftCharts Not Showing Accurate Data Until Tap Gesture on Chart
I am showing weather data in a TabView where each tab will show the forecast for that day and then an hour-by-hour Swift Charts of the temperature, chance of precipitation, and then dew point for that day. The day and a text description of that forecast correctly displays for each tab. However, the chart will only show the correct data if you perform a tap gesture on the chart. To reproduce this issue, I do the following: Tap on a day in the "Upcoming Week", preferably a day in the middle. Swipe a couple days to the left or right and use the tap gesture on one of the charts. Oddly, other data on the tab is accurate, it is really just within the SwiftChart. I did try doing a horizontal ScrollView instead but I had the same issue. I also followed the demo for SwiftCharts from WWDC. Below is code that shows the TabView: struct UpcomingDaysView: View { let forecastModel:WeatherModel @State var targetPeriod:WeatherForecastDayPeriod var body: some View { TabView(selection:$targetPeriod) { ForEach(forecastModel.dailyPeriods, id: \.self) {period in DailyViewChartDetail(forecastModel: forecastModel, periodToShow: period) .frame(alignment: .topLeading) .tag(period) } } .containerRelativeFrame([.vertical]) .tabViewStyle(.page) .indexViewStyle(.page(backgroundDisplayMode: .always)) .padding(EdgeInsets(top: 20, leading: 0, bottom: 0, trailing: 0)) } } } And here is the DailyViewChartDetail: struct DailyViewChartDetail: View { var forecastModel:WeatherModel var periodToShow:WeatherForecastDayPeriod var body: some View { VStack { Text("\(DateUtility.getLongerDay(date: DateUtility.getDate(stringDate: periodToShow.dayForecast.startTime)))") .font(.title2) Text("\(periodToShow.dayForecast.detailedForecast)") .font(.subheadline) .padding(5) HourlyViewChart(forecastModel: WeatherPeriodUtility.filterModel(forecastModel: forecastModel, targetPeriod: periodToShow)) .padding(5) Spacer() } .frame( alignment: .topLeading ) } } And then some of the more relevant code in the HourlyViewChart struct HourlyViewChart: View { var forecastModel:WeatherModel @State var range: (Date, Date)? = nil @State var rawSelectedDateTemp: Date? = nil @State var rawSelectedDatePrecipitation: Date? = nil @State var rawSelectedDewPoint: Date? = nil // ... more code Below is an image that shows the issue:
Replies
2
Boosts
0
Views
908
Activity
Aug ’24
How to show scroll bars on a Swift Chart for macOS?
(I'm using macOS 14.5 and Xcode 15.4) I have a Swift Chart on macOS that needs to scroll horizontally. Simplified version: Chart(dataPoints) { data in LineMark(x: .value("X Axis", data.x), y: .value("Y Axis", data.y)) } .chartScrollableAxes(.horizontal) .chartXVisibleDomain(length: 10) The above code works fine, except that it does not show scroll bars. On a Mac with no trackpad, this means there's no mechanism to scroll the chart. On my MacBook Pro with a trackpad, I can scroll the chart with a 2-finger swipe gesture, but there are no transient scroll bars to show the relative size of the visible part of the chart. How do I add visible scroll bars to the chart so that I can scroll on Macs with no trackpad?
Replies
0
Boosts
0
Views
599
Activity
Jul ’24
Swift Charts: Changing chartXVisibleDomain changes chartScrollPosition
I'm building a Swift Chart that displays locations in a horizontal timeline. The chart is scrollable. Unfortunately, when chartScrollPosition is offset by some amount (i.e. the user has scrolled the chart), changing chartXVisibleDomain results in chartScrollPosition jumping backwards by some amount. This results in bad user experience. A minimum reproducible example is below. To reproduce: Run the code below Using the picker, change chartXVisibleDomain. ThechartScrollPosition remains the same, as expected. Scroll the chart on the horizontal axis. Using the picker, change chartXVisibleDomain. ThechartScrollPosition changes unexpectedly. You can verify this by watching the labels at the bottom of the chart. The chart simply ends up showing a different area of the domain. Tested on various iPhone and iPad simulators and physical devices, the issue appears everywhere. Is this a SwiftUI bug, or am I doing something wrong? struct ScrollableChartBug: View { /// Sample data let data = SampleData.samples let startDate = SampleData.samples.first?.startDate ?? Date() let endDate = Date() /// Scroll position of the chart, expressed as Date along the x-axis. @State var chartPosition: Date = SampleData.samples.first?.startDate ?? Date() /// Sets the granularity of the shown view. @State var visibleDomain: VisibleDomain = .year var body: some View { Chart(data, id: \.id) { element in BarMark(xStart: .value("Start", element.startDate), xEnd: .value("End", element.endDate), yStart: 0, yEnd: 50) .foregroundStyle(by: .value("Type", element.type.rawValue)) .clipShape(.rect(cornerRadius: 8, style: .continuous)) } .chartScrollableAxes(.horizontal) // enable scroll .chartScrollPosition(x: $chartPosition) // track scroll offset .chartXVisibleDomain(length: visibleDomain.seconds) .chartXScale(domain: startDate...endDate) .chartForegroundStyleScale { typeName in // custom colors for bars and for legend SampleDataType(rawValue: typeName)?.color ?? .clear } .chartXAxis { AxisMarks(values: .stride(by: .month, count: 1)) { value in if let date = value.as(Date.self) { AxisValueLabel { Text(date, format: .dateTime.year().month().day()) .bold() } AxisTick(length: .label) } } } .frame(height: 90) .padding(.bottom, 40) // for overlay picker .overlay { Picker("", selection: $visibleDomain.animation()) { ForEach(VisibleDomain.allCases) { variant in Text(variant.label) .tag(variant) } } .pickerStyle(.segmented) .frame(width: 240) .padding(.trailing) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing) } //: overlay } //: body } //: struct // MARK: - Preview #Preview { ScrollableChartBug() } // MARK: - Data enum SampleDataType: String, CaseIterable { case city, wood, field var color: Color { switch self { case .city: .gray case .wood: .green case .field: .brown } } var label: String { switch self { case .city: "City" case .wood: "Wood" case .field: "Field" } } } enum VisibleDomain: Identifiable, CaseIterable { case day case week case month case year var id: Int { self.seconds } var seconds: Int { switch self { case .day: 3600 * 24 * 2 case .week: 3600 * 24 * 10 case .month: 3600 * 24 * 40 case .year: 3600 * 24 * 400 } } var label: String { switch self { case .day: "Days" case .week: "Weeks" case .month: "Months" case .year: "Years" } } } struct SampleData: Identifiable { let startDate: Date let endDate: Date let name: String let type: SampleDataType var id: String { name } static let samples: [SampleData] = [ .init(startDate: Date.from(year: 2022, month: 3, day: 1), endDate: Date.from(year: 2022, month: 3, day: 10), name: "New York", type: .city), .init(startDate: Date.from(year: 2022, month: 3, day: 20, hour: 6), endDate: Date.from(year: 2022, month: 5, day: 1), name: "London", type: .city), .init(startDate: Date.from(year: 2022, month: 5, day: 4), endDate: Date.from(year: 2022, month: 7, day: 5), name: "Backcountry ABC", type: .field), .init(startDate: Date.from(year: 2022, month: 7, day: 5), endDate: Date.from(year: 2022, month: 10, day: 10), name: "Field DEF", type: .field), .init(startDate: Date.from(year: 2022, month: 10, day: 10), endDate: Date.from(year: 2023, month: 2, day: 10), name: "Wood 123", type: .wood), .init(startDate: Date.from(year: 2023, month: 2, day: 10), endDate: Date.from(year: 2023, month: 3, day: 20), name: "Paris", type: .city), .init(startDate: Date.from(year: 2023, month: 3, day: 21), endDate: Date.from(year: 2023, month: 10, day: 5), name: "Field GHI", type: .field), .init(startDate: Date.from(year: 2023, month: 10, day: 5), endDate: Date.from(year: 2024, month: 3, day: 5), name: "Wood 456", type: .wood), .init(startDate: Date.from(year: 2024, month: 3, day: 6), endDate: Date(), name: "Field JKL", type: .field) ] } extension Date { /** Constructs a Date from a given year (Int). Use like `Date.from(year: 2020)`. */ static func from(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil) -> Date { let components = DateComponents(year: year, month: month, day: day, hour: hour, minute: minute) guard let date = Calendar.current.date(from: components) else { print(#function, "Failed to construct date. Returning current date.") return Date() } return date } }
Replies
3
Boosts
2
Views
1.8k
Activity
Jul ’24
Swift Charts: .hour annotations do not appear
I'm building a Swift Chart that displays locations in a horizontal timeline. The chart is scrollable. When the chart is zoomed in, I want to show an annotation for every 6 hours. Unfortunately, when axisMarks are set to .stride(by: .hour, count: 6), the annotations do not appear for the first several months in the timeline. I tried setting .stride(by: .minute, count: 360), but the result is the same. Is this a Swift Charts bug, or am I doing something wrong? A reproducible example is below. To reproduce: Run the code below See that annotations are missing at the leading edge of the chart. They only show up from a certain point on the chart's domain. Tested on various iPhone and iPad simulators and physical devices, the issue appears everywhere. P.S. I am aware that the example code below is not performant and that the annotations overlap when the chart is zoomed out. I have workarounds for that, but it's beyond the scope of my question and the minimum reproducible example. struct ChartAnnotationsBug: View { /// Sample data let data = SampleData.samples let startDate = SampleData.samples.first?.startDate ?? Date() let endDate = Date() /// Scroll position of the chart, expressed as Date along the x-axis. @State var chartPosition: Date = SampleData.samples.first?.startDate ?? Date() /// Sets the granularity of the shown view. @State var visibleDomain: VisibleDomain = .month var body: some View { Chart(data, id: \.id) { element in BarMark(xStart: .value("Start", element.startDate), xEnd: .value("End", element.endDate), yStart: 0, yEnd: 50) .foregroundStyle(by: .value("Type", element.type.rawValue)) .clipShape(.rect(cornerRadius: 8, style: .continuous)) } .chartScrollableAxes(.horizontal) // enable scroll .chartScrollPosition(x: $chartPosition) // track scroll offset .chartXVisibleDomain(length: visibleDomain.seconds) .chartXScale(domain: startDate...endDate) .chartXAxis { AxisMarks(values: .stride(by: .hour, count: 6)) { value in if let date = value.as(Date.self) { let hour = Calendar.current.component(.hour, from: date) if hour == 0 { // midnight AxisValueLabel(collisionResolution: .truncate) { VStack(alignment: .leading) { Text(date, format: .dateTime.hour().minute()) Text(date, format: .dateTime.weekday().month().day()) .bold() } } AxisTick(stroke: .init(lineWidth: 1)) } else if [6, 12, 18].contains(hour) { // period AxisValueLabel(collisionResolution: .truncate) { Text(date, format: .dateTime.hour().minute()) } AxisTick(length: .label) } } } } .frame(height: 100) .padding(.bottom, 40) // for overlay picker .overlay { Picker("", selection: $visibleDomain.animation()) { ForEach(VisibleDomain.allCases) { variant in Text(variant.label) .tag(variant) } } .pickerStyle(.segmented) .frame(width: 240) .padding(.trailing) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing) } //: overlay } //: body } //: struct // MARK: - Preview #Preview { ChartAnnotationsBug() } // MARK: - Data enum SampleDataType: String, CaseIterable { case city, wood, field var label: String { switch self { case .city: "City" case .wood: "Wood" case .field: "Field" } } } enum VisibleDomain: Identifiable, CaseIterable { case day case week case month var id: Int { self.seconds } var seconds: Int { switch self { case .day: 3600 * 24 * 2 case .week: 3600 * 24 * 10 case .month: 3600 * 24 * 40 } } var label: String { switch self { case .day: "Days" case .week: "Weeks" case .month: "Months" } } } struct SampleData: Identifiable { let startDate: Date let endDate: Date let name: String let type: SampleDataType var id: String { name } static let samples: [SampleData] = [ .init(startDate: Date.from(year: 2024, month: 3, day: 1, hour: 23, minute: 59), endDate: Date.from(year: 2024, month: 3, day: 10), name: "New York", type: .city), .init(startDate: Date.from(year: 2024, month: 3, day: 10, hour: 6), endDate: Date.from(year: 2024, month: 3, day: 20), name: "London", type: .city), .init(startDate: Date.from(year: 2024, month: 3, day: 20), endDate: Date.from(year: 2024, month: 4, day: 10), name: "Backcountry ABC", type: .field), .init(startDate: Date.from(year: 2024, month: 4, day: 10), endDate: Date.from(year: 2024, month: 4, day: 20), name: "Field DEF", type: .field), .init(startDate: Date.from(year: 2024, month: 4, day: 20), endDate: Date.from(year: 2024, month: 5, day: 10), name: "Wood 123", type: .wood), .init(startDate: Date.from(year: 2024, month: 5, day: 10), endDate: Date.from(year: 2024, month: 5, day: 20), name: "Paris", type: .city), .init(startDate: Date.from(year: 2024, month: 5, day: 20), endDate: Date.from(year: 2024, month: 6, day: 5), name: "Field GHI", type: .field), .init(startDate: Date.from(year: 2024, month: 6, day: 5), endDate: Date.from(year: 2024, month: 6, day: 10), name: "Wood 456", type: .wood), .init(startDate: Date.from(year: 2024, month: 6, day: 10), endDate: Date(), name: "Field JKL", type: .field) ] } extension Date { /** Constructs a Date from a given year (Int). Use like `Date.from(year: 2020)`. */ static func from(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil) -> Date { let components = DateComponents(year: year, month: month, day: day, hour: hour, minute: minute) guard let date = Calendar.current.date(from: components) else { print(#function, "Failed to construct date. Returning current date.") return Date() } return date } }
Replies
3
Boosts
2
Views
1.3k
Activity
Jul ’24