Chapter 48
Building Pie Charts and Donut Charts
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. In chapter 8, we showed you a technique on implementing pie charts and donut charts from scratch. However, since the 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 chapter, 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.
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)
]
These are just some random data on coffee sales for chart rendering. For simplicity, I used an array of tuples to hold the data. The Charts framework makes it very easy for developers to create a bar chart from these data.
First, import the Charts framework and replace the body part with the following code:
VStack {
Chart {
ForEach(coffeeSales, id: \.name) { coffee in
BarMark(
x: .value("Type", coffee.name),
y: .value("Cup", coffee.count)
)
.foregroundStyle(by: .value("Type", coffee.name))
}
}
}
.padding()
Whether you're creating a bar chart or a pie chart, it all starts with the Chart view. Within this view, we define a set of BarMark for rendering a vertical bar chart that plots coffee types on the x-axis and counts on the y-axis. The foregroundStyle modifier automatically assigns a unique color for each of the bars.

You can easily create a different type of bar chart by altering some of the BarMark parameters.

For example, if you want to create a one dimensional bar chart, you just need to provide the values for the x or y axis:
To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.