Visualizing Data with Swift Charts: Displaying multiple datasets
Last time, I explored the magic of Swift Charts for crafting stunning and informative charts in your SwiftUI app. But what if your data has multiple stories to tell?
Swift Charts shines when you need to display multiple datasets within a single chart. This allows you to compare trends, identify correlations, and paint a richer picture for your users.
How to do it?
First start by adding another set of performance data:
var secondStoresPerfInfo: [PerformanceInfo] = [
.init(stores: 0, rating: 3),
.init(stores: 1, rating: 2),
.init(stores: 2, rating: 4),
.init(stores: 3, rating: 5),
.init(stores: 4, rating: 1),
.init(stores: 5, rating: 3)
]
Then, Let’s add the new set and join it with the old set in a tuple array:
let multiplePerformers = [
(name: "First Store", info: storesPerfInfo),
(name: "Second Store", info: secondStoresPerfInfo),
]
Now, Because the structure of the data has changed, I will instead feed Chart
with multiplePerformers
, and wrap BarMark
with ForEach
based on each perfomer.info
:
Chart (multiplePerformers, id: \.name) { performer in
ForEach(performer.info) { perfInfo in
BarMark(
x: .value("Store ID", perfInfo.stores),
y: .value("Rating", perfInfo.rating)
)
}
}
Last but not least, I will add one modifier to BarMark
to change the foreground color of each set:
.foregroundStyle(by: .value("Performer", performer.name))
I will add another modifier to offset each set’s mark:
.position(by: .value("Performer", performer.name), axis: .horizontal, span: .inset(15))
That’s it. By leveraging multiple datasets, you can unlock new levels of data exploration within your app. Imagine a fitness app displaying calories burned alongside distance traveled, or a finance app charting stock prices against market trends. The possibilities are endless!
Ready to Dive Deeper?
Apple’s documentation provides in-depth examples of working with multiple datasets in Swift Charts. Additionally, the developer community offers a wealth of tutorials and code samples to inspire you.
So, unleash the full potential of your data with Swift Charts! Craft compelling charts that showcase multiple datasets, and empower your users to make informed decisions based on the rich insights you provide.
To access the code discussed in this post, visit here.