I want to visualize the data stored in a DataFrame using various charts (barmark, sectormark, linemark, etc.).
My questions are as follows:
Can a DataFrame be used directly within a chart? If so, could you provide a simple example?
If it cannot be used directly, what is the correct way to use it? Could you provide an example?
Thank you for your help.
Best regards.
Swift Charts
RSS for tagVisualize data with highly customizable charts across all Apple platforms using the compositional syntax of SwifUI.
Posts under Swift Charts tag
53 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I am trying to discover how to display my application’s calculated Solar Information values in a chart.
My application identifies a selected location in MapKit.
The application identifies the location’s longitude, latitude, and current time of day.
The application calculates the selected location’s NOAA [SOLAR ELEVATION], and the [SOLAR AZIMUTH] for the time of day.
The application calculates the data, then stores the calculated values as a [Plist] file within my application’s Document Directory.
For the moment, complete with repeated scouring of the Internet, I am not sure how to properly convert, transfer, or create a Structure, required by the chart to display the calculated values. I would like to create the chart once the calculations are complete, but I introduced a Plist to store the calculations for future use, too.
The calculated values coincide with the NOAA Solar Calculations, complete to the displayed [h : m : s], whereas I also designed the application to create the [Array of Dictionary Objects] to store the calculated values for each subsequent six minute interval, until the end of the selected location’s day. The calculated values are properly appended to the [Array of Dictionary Objects] after each completed calculation, with data transfer constants. There are 240 calculations per day from [00:06:00 to 23:54:00], presented as a [STRING], complete with the [Elevation] presented as a [DOUBLE].
For example :: The application generates the following [Calculated Array of Dictionary Objects], then recreates, and appends a new Plist in the Document Directory.
mySolarElevationDataArrayOfDictionaries :: [(theRequiredTimeOfDay: "00:06:00", theCalculatedElevation: -62.60301082991259), (theRequiredTimeOfDay: "00:12:00", theCalculatedElevation: -62.94818095051292), (theRequiredTimeOfDay: "00:18:00", theCalculatedElevation: -63.245198186807215), (theRequiredTimeOfDay: "00:24:00", theCalculatedElevation: -63.49236786176319), (theRequiredTimeOfDay: "00:30:00", theCalculatedElevation: -63.688223890934175), (theRequiredTimeOfDay: "00:36:00", theCalculatedElevation: -63.831564163806945), (theRequiredTimeOfDay: "00:42:00", theCalculatedElevation: -63.921486675739004), (theRequiredTimeOfDay: "00:48:00", theCalculatedElevation: -63.95741610687708), to the end of the data :: ===> (theRequiredTimeOfDay: "23:54:00", theCalculatedElevation: -60.69355458181633)]
The application presents the initial data as follows ::
Then presents a compass view to illustrate the results ::
I modified the Chart’s [MOCK DATA] from the calculated values to test the Chart’s display in a [SwiftUI Hosting Controller].
For example :: The following Chart Mock Data in a [HourlySunElevation_MockChartData.swift] file is called by the application’s [Content View].
import Foundation
struct Value {
let theRequiredTimeOfDay: String
let theCalculatedElevation: Double
static func theSunElevationMockData() -> [Value] {
return [Value(theRequiredTimeOfDay: "00:06:00", theCalculatedElevation: -62.60301082991259), Value(theRequiredTimeOfDay: "00:12:00", theCalculatedElevation: -62.94818095051292), Value(theRequiredTimeOfDay: "00:18:00", theCalculatedElevation: -63.245198186807215), Value(theRequiredTimeOfDay: "00:24:00", theCalculatedElevation: -63.49236786176319), Value(theRequiredTimeOfDay: "00:30:00", theCalculatedElevation: -63.688223890934175), Value(theRequiredTimeOfDay: "00:36:00", theCalculatedElevation: -63.831564163806945), Value(theRequiredTimeOfDay: "00:42:00", theCalculatedElevation: -63.921486675739004), Value(theRequiredTimeOfDay: "00:48:00", theCalculatedElevation: -63.95741610687708), to the end of the data :: ===> Value(theRequiredTimeOfDay: "23:54:00", theCalculatedElevation: -60.69355458181633)]
The Chart illustrates the Mock Data as follows ::
I also created a Struct within the [MySunElevationChart_ViewController] to try to append the calculated data, using the same logic with the Plist data transfer constants, as employed by the [Array of Dictionary Objects] ::
struct ChartSolarElevationValues {
var theRequiredTimeOfDay: String
var theCalculatedElevation: Double
// Structs have an implicit [init]. This is here for reference.
init(theRequiredTimeOfDay: String, theCalculatedElevation: Double) {
self.theRequiredTimeOfDay = theRequiredTimeOfDay
self.theCalculatedElevation = theCalculatedElevation
//mySolarElevationChartData.append(self)
} // End of [init(theRequiredTimeOfDay: String, theCalculatedElevation: Double)]
} // End of [struct ChartSolarElevationValues]
Unfortunately, the result did not append each subsequent calculation, but continued to create the same calculation as a new distinct object ::
NOTE :: I only called three calculations with the Struct test.
// NOTE :: To prevent an [ERROR] at [var mySolarElevationChartData = [ChartSolarElevationValues]] since it has an init.
// Therefore you must add () at the end of [var mySolarElevationChartData = [ChartSolarElevationValues]]
let theData = [ChartSolarElevationValues]()
//print("theData :: \(theData)\n")
let someData = ChartSolarElevationValues(theRequiredTimeOfDay: TheTimeForDaySunElevation.theTheTimeForDaySunElevation, theCalculatedElevation:VerifyCityLocationSearchRequestCorrectedSolarElevation.theVerifyCityLocationSearchRequestCorrectedSolarElevation)
var theData_New = theData
theData_New.append(someData)
print("theData_New :: \(theData_New)\n")
// Prints :: theData_New :: [My_Map.ChartSolarElevationValues(theRequiredTimeOfDay: "00:06:00", theCalculatedElevation: -61.11000735370401)]]
// Prints :: [theData_New :: [My_Map.ChartSolarElevationValues(theRequiredTimeOfDay: "00:12:00", theCalculatedElevation: -61.315092082911875)]]
// Prints :: [theData_New :: [My_Map.ChartSolarElevationValues(theRequiredTimeOfDay: "00:18:00", theCalculatedElevation: -61.47403413313205)]]
So, I am misintepreting the required coding structure to properly append the Elevation Chart, and the Azimuth Chart with the calculated data.
I know something is amiss, but for the moment, I do not know how to address this issue.
Your suggestions would be welcome ... :]
jim_k
Does SwiftUI now support the ability for a chart to have two different Y Axes? ChaptGPT seems to think it does, but I keep getting compiler errors in XCode.
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)
}
}
}
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.
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)")
}
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.
In creating a sequenced gesture combining a LongPressGesture and a DragGesture, I found that the combined gesture exhibits two problems:
The @GestureState does not properly update as the gesture progresses through its phases. Specifically, the updating(_:body:) closure (documented here) is only ever executed during the drag interaction. Long presses and drag-releases do not call the updating(_:body:) closure.
Upon completing the long press gesture and activating the drag gesture, the drag gesture remains empty until the finger or cursor has moved. The expected behavior is for the drag gesture to begin even when its translation is of size .zero.
This second problem – the nonexistence of a drag gesture once the long press has completed – prevents access to the location of the long-press-then-drag. Access to this location is critical for displaying to the user that the drag interaction has commenced.
The below code is based on Apple's example presented here. I've highlighted the failure points in the code with // *.
My questions are as follows:
What is required to properly update the gesture state?
Is it possible to have a viable drag gesture immediately upon fulfilling the long press gesture, even with a translation of .zero?
Alternatively to the above question, is there a way to gain access to the location of the long press gesture?
import SwiftUI
import Charts
enum DragState {
case inactive
case pressing
case dragging(translation: CGSize)
var isDragging: Bool {
switch self {
case .inactive, .pressing:
return false
case .dragging:
return true
}
}
}
struct ChartGestureOverlay<Value: Comparable & Hashable>: View {
@Binding var highlightedValue: Value?
let chartProxy: ChartProxy
let valueFromChartProxy: (CGFloat, ChartProxy) -> Value?
let onDragChange: (DragState) -> Void
@GestureState private var dragState = DragState.inactive
var body: some View {
Rectangle()
.fill(Color.clear)
.contentShape(Rectangle())
.onTapGesture { location in
if let newValue = valueFromChartProxy(location.x, chartProxy) {
highlightedValue = newValue
}
}
.gesture(longPressAndDrag)
}
private var longPressAndDrag: some Gesture {
let longPress = LongPressGesture(minimumDuration: 0.2)
let drag = DragGesture(minimumDistance: .zero)
.onChanged { value in
if let newValue = valueFromChartProxy(value.location.x, chartProxy) {
highlightedValue = newValue
}
}
return longPress.sequenced(before: drag)
.updating($dragState) { value, gestureState, _ in
switch value {
case .first(true):
// * This is never called
gestureState = .pressing
case .second(true, let drag):
// * Drag is often nil
// * When drag is nil, we lack access to the location
gestureState = .dragging(translation: drag?.translation ?? .zero)
default:
// * This is never called
gestureState = .inactive
}
onDragChange(gestureState)
}
}
}
struct DataPoint: Identifiable {
let id = UUID()
let category: String
let value: Double
}
struct ContentView: View {
let dataPoints = [
DataPoint(category: "A", value: 5),
DataPoint(category: "B", value: 3),
DataPoint(category: "C", value: 8),
DataPoint(category: "D", value: 2),
DataPoint(category: "E", value: 7)
]
@State private var highlightedCategory: String? = nil
@State private var dragState = DragState.inactive
var body: some View {
VStack {
Text("Bar Chart with Gesture Interaction")
.font(.headline)
.padding()
Chart {
ForEach(dataPoints) { dataPoint in
BarMark(
x: .value("Category", dataPoint.category),
y: .value("Value", dataPoint.value)
)
.foregroundStyle(highlightedCategory == dataPoint.category ? Color.red : Color.gray)
.annotation(position: .top) {
if highlightedCategory == dataPoint.category {
Text("\(dataPoint.value, specifier: "%.1f")")
.font(.caption)
.foregroundColor(.primary)
}
}
}
}
.frame(height: 300)
.chartOverlay { chartProxy in
ChartGestureOverlay<String>(
highlightedValue: $highlightedCategory,
chartProxy: chartProxy,
valueFromChartProxy: { xPosition, chartProxy in
if let category: String = chartProxy.value(atX: xPosition) {
return category
}
return nil
},
onDragChange: { newDragState in
dragState = newDragState
}
)
}
.onChange(of: highlightedCategory, { oldCategory, newCategory in
})
}
.padding()
}
}
#Preview {
ContentView()
}
Thank you!
I'm trying to make a Swift Chart where 24 AreaMarks an hour apart on X axis over a day display a vertical gradient.
The gradient is vertical and is essentially [Color.opacity(0.1),Colour,Color.opacity(0.1]
The idea here is where the upper and lower points of each AreaMark are the same or close to each other in the Y axis, the chart essentially displays a line, where they are far apart you get a nice fading vertical gradient.
However, it seems that the .alignsMarkStylesWithPlotArea modifier is always set for AreaMarks even if manually applying it false.
Investigating further, I've learnt that with AreaMarks in a series, Swift Charts seems to only listen to the first foreground style set in. I've created some sample code to demonstrate this.
struct DemoChartView: View {
var body: some View {
Chart {
AreaMark(x: .value("Time", Date().addingTimeInterval(0)), yStart: .value("1", 40), yEnd: .value("2", 60))
.foregroundStyle(LinearGradient(colors: [.pink, .teal], startPoint: .top, endPoint: .bottom))
.alignsMarkStylesWithPlotArea(false)
AreaMark(x: .value("Time", Date().addingTimeInterval(3600)), yStart: .value("1", 44), yEnd: .value("2", 58))
.foregroundStyle(LinearGradient(colors: [.orange, .yellow], startPoint: .top, endPoint: .bottom))
.alignsMarkStylesWithPlotArea(false)
AreaMark(x: .value("Time", Date().addingTimeInterval(03600*2)), yStart: .value("1", 50), yEnd: .value("2", 90))
.foregroundStyle(LinearGradient(colors: [.green, .blue], startPoint: .top, endPoint: .bottom))
.alignsMarkStylesWithPlotArea(false)
}
}
}
Which produces this:
So here, all the different .foregroundStyle LinearGradients are being ignored AND the .alignsMarkStylesWithPlotArea(false) is also ignored - the amount of pink on the first mark is different to the second and third 🤷♂️
Has anyone encountered this. Are AreaMarks the correct choice or are they just not setup to create this type of data display. Thanks
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?
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.
Using just basic rule
.chartScrollableAxes(.horizontal)
.chartXVisibleDomain(length: 6)
Feature is working fine for iOS 17.x devices
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?
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)
}
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
Hello there!
I wanted to give a native scrolling mechanism for the Swift Charts Graph a try and experiment a bit if the scenario that we try to achieve might be possible, but it seems that the Swift Charts scrolling performance is very poor.
The graph was created as follows:
X-axis is created based on a date range,
Y-axis is created based on an integer values between moreless 0-320 value.
the graph is scrollable horizontally only (x-axis),
The time range (x-axis) for the scrolling content was set to one year from now date (so the user can scroll one year into the past as a minimum visible date (.chartXScale).
The X-axis shows 3 hours of data per screen width (.chartXVisibleDomain).
The data points for the graph are generated once when screen is about to appear so that the Charts engine can use it (no lazy loading implemented yet).
The line data points (LineMark views) consist of 2880 data points distributed every 5 minutes which simulates - two days of continuous data stream that we want to present. The rest of the graph displays no data at all.
The performance result:
The graph on the initial loading phase is frozen for about 10-15 seconds until the data appears on the graph.
Scrolling is very laggy - the CPU usage is 100% and is unacceptable for the end users.
If we show no data at all on the graph (so no LineMark views are created at all) - the result is similar - the empty graph scrolling is also very laggy.
Below I am sharing a test code:
@main
struct ChartsTestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
Spacer()
}
}
}
struct LineDataPoint: Identifiable, Equatable {
var id: Int
let date: Date
let value: Int
}
actor TestData {
func generate(startDate: Date) async -> [LineDataPoint] {
var values: [LineDataPoint] = []
for i in 0..<(1440 * 2) {
values.append(
LineDataPoint(
id: i,
date: startDate.addingTimeInterval(
TimeInterval(60 * 5 * i) // Every 5 minutes
),
value: Int.random(in: 1...100)
)
)
}
return values
}
}
struct ContentView: View {
var startDate: Date {
return endDate.addingTimeInterval(-3600*24*30*12) // one year into the past from now
}
let endDate = Date()
@State var dataPoints: [LineDataPoint] = []
var body: some View {
Chart {
ForEach(dataPoints) { item in
LineMark(
x: .value("Date", item.date),
y: .value("Value", item.value),
series: .value("Series", "Test")
)
}
}
.frame(height: 200)
.chartScrollableAxes(.horizontal)
.chartYAxis(.hidden)
.chartXScale(domain: startDate...endDate) // one year possibility to scroll back
.chartXVisibleDomain(length: 3600 * 3) // 3 hours visible on screen
.onAppear {
Task {
dataPoints = await TestData().generate(startDate: startDate)
}
}
}
}
I would be grateful for any insights or suggestions on how to improve it or if it's planned to be improved in the future.
Currently, I use UIKit CollectionView where we split the graph into smaller chunks of the graph and we present the SwiftUI Chart content in the cells, so we use the scrolling offered there. I wonder if it's possible to use native SwiftUI for such a scenario so that later on we could also implement some kind of lazy loading of the data as the user scrolls into the past.
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.
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.
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?
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