Creating Pie Charts and Donut Charts Using SwiftUI in iOS 17
Pie charts and donut charts are two popular chart types used in data visualization. Prior to iOS 17, if you want to create these types of charts using SwiftUI, you’ll have to build the charts on your own using components like Path
and Arc
. Previously, we wrote a detailed tutorial on how to implement pie charts and donut charts from scratch. However, in the upcoming release of iOS 17, this is no longer necessary. SwiftUI simplifies the process of creating these charts by introducing a new mark type called SectorMark
. This makes it easy for developers to build all kinds of pie and donut charts.
In this tutorial, we will guide you through the process of building pie charts and donut charts using SwiftUI. On top of that, you’ll also learn how to add interactivity to the charts.
To follow the code sample of this tutorial, please make sure you use Xcode 15 (Beta 2 or up).
Revisiting Bar Charts
Let’s start by implementing a simple bar chart using the Charts framework. Assuming you have created a new SwiftUI project, insert the lines of code below to initialize the sample data for the bar chart:
private var coffeeSales = [
(name: "Americano", count: 120),
(name: "Cappuccino", count: 234),
(name: "Espresso", count: 62),
(name: "Latte", count: 625),
(name: "Mocha", count: 320),
(name: "Affogato", count: 50)
]