Charts In SwiftUI

Introduction

At WWDC 2022, Apple introduced Swift Charts. This is Apple's new framework for making informative and easy-to-understand charts in SwiftUI. In this world, we deal with a lot of data. So, it is important to understand the data so that we can understand the world and make better decisions. Data alone is of little use; to make it useful, we must make sense of it. We can understand complex data with well-designed and accessible data visualization. We use charts for a better understanding of data, such as fluctuations in stock prices over some time ranges, heart rates during exercise, temperatures over time, and many more things.

Swift Charts

Swift Charts is a flexible and powerful framework for making Apple-designed charts. It uses the same syntax as SwiftUI, which means that we already know the language of Swift Charts. We will understand SwiftCharts using some examples. Let's say on a table there are different shapes of glasses in different colors. Here we will plot a chart that will visualize all data related to these glasses. To make this visualization in SwiftCharts, we can use the same syntax as what we'd use in SwiftUI. The main components of the BarChart are the bars, which are visual elements for each item in our data. In SwiftCharts, these visual elements are called Marks.

Let's jump into Xcode

We have different shapes and colors of glasses. We will plot a chart that will show how many numbers of cubes, spheres, and pyramids there are, and which colors appear the most. Let's create data to show in our charts.

struct GlassShape: Identifiable {
    var type: String
    var count: Double
    var id = UUID()
}

Here we have created a struct that has variable types, count, and id, which means that every shape has its own unique id.

Now we will create an array of struct GlassShape, which will contain all the data regarding the glasses.

var data: [GlassShape] = [
    .init(type: "Cube", count: 5),
    .init(type: "Sphere", count: 4),
    .init(type: "Pyramid", count: 4)
]

Initialization of Chart

Here we will create a new SwiftUI project. In the ContentView.swift file, we will import Charts that will be available only in the Xcode 14 beta version. If you are using another version, you will not be able to import Charts.

import SwiftUI
import Charts

struct GlassChart: View {
    var body: some View {
        Chart {
            // Add marks here.
        }
    }
}

Here we have created an empty Chart container. In the Chart container, we will specify our data. We can specify marks using BarMark, LineMark, or PointMark. We use LineMarks to visualize the data with lines of a chart, and PointMark to show the points on a chart, called a Scatter plot. We will use the BarMark here, which shows the bar on the chart.

Chart {
    BarMark(
        x: .value("Shape Type", data[0].type),
        y: .value("Total Count", data[0].count)
    )
    BarMark(
         x: .value("Shape Type", data[1].type),
         y: .value("Total Count", data[1].count)
    )
    BarMark(
         x: .value("Shape Type", data[2].type),
         y: .value("Total Count", data[2].count)
    )
}

Result:


figure 1 source: "Apple Developer's  Documentation"

In the result, we see a chart that shows that there are three bars. These bars show three shapes of glasses. Charts make data easy to understand. Here, we have the X and Y axis. The X axis shows three bars called Cube, Pyramid, and Sphere. In the Y axis, we have counts, like five Cubes and four Pyramids and four Spheres.

This was the example of BarMark. We also can use the ForEach loop here, since we are getting data in a repetitive manner. This will reduce our lines of code.

Chart {
    ForEach(data) { shape in
        BarMark(
            x: .value("Shape Type", shape.type),
            y: .value("Total Count", shape.count)
        )
    }
}

Adding a color property to data

We have plotted a chart here, where we see different shapes of glasses and their amounts. But what if we also have different colors for each shape? SwiftUI Chart can represent not only the amounts of items but also the distribution of colors among each glass. Now we will add one more parameter to the GlassShape structure.

struct GlassShape: Identifiable {
    var color: String
    var type: String
    var count: Double
    var id = UUID()
}

Now we have to again initialize our array named data.

var data: [GlassShape] = [
    .init(color: "Green", type: "Cube", count: 2),
    .init(color: "Green", type: "Sphere", count: 0),
    .init(color: "Green", type: "Pyramid", count: 1),
    .init(color: "Purple", type: "Cube", count: 1),
    .init(color: "Purple", type: "Sphere", count: 1),
    .init(color: "Purple", type: "Pyramid", count: 1),
    .init(color: "Pink", type: "Cube", count: 1),
    .init(color: "Pink", type: "Sphere", count: 2),
    .init(color: "Pink", type: "Pyramid", count: 0),
    .init(color: "Yellow", type: "Cube", count: 1),
    .init(color: "Yellow", type: "Sphere", count: 1),
    .init(color: "Yellow", type: "Pyramid", count: 2)
]

Here we will use an additional property of BarMark, which is ".foregroundStyle(by: )" This is used to represent the distribution of colors.

Chart {
    ForEach(data) { shape in
        BarMark(
            x: .value("Shape Type", shape.type),
            y: .value("Total Count", shape.count)
        )
        .foregroundStyle(by: .value("Shape Color", shape.color))
    }
}

Result:


figure 2 source: "Apple Developer's  Documentation"

In the result, we see a chart that represents the amount of different shapes of glasses in a particular color. For example, here we can see we have two cubes that are red.

Conclusion

SwiftChart is a great tool that we will use, because a chart is something many use in their daily lives, especially if we want to do something like show the population of a country. We simply cannot show only the data. Well, we can, but we will not get much from that. Using charts, we can easily represent the population for a country within different years. I hope you understand SwiftCharts.  SwiftChart is an important topic that we will use in our iOS apps, so practice charts in SwiftUI. To read more about SwiftUI Chart click here.

Thanks for reading this article.

In WWDC 2022 Apple also introduced MacOS 13, to know more about MacOS 13 read my full article What's New In MacOS 13


Similar Articles