Tuesday, February 7, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

Creating a Line Chart Using SwiftUI Charts API

learningcode_x1mckf by learningcode_x1mckf
September 7, 2022
in Swift
0
Creating a Line Chart Using SwiftUI Charts API
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


The Charts framework is one among my favorite options for the brand new model of SwiftUI in iOS 16. Previous to iOS 16, you have to construct your individual charts or depend on third social gathering library to render charts for you. With the discharge of this new framework, Apple has made it very simple for builders to create animated and interactive charts.

You might also like

The abstract Vapor service factory design pattern

SwiftNIO tutorial – The echo server

Introducing – Vapor cheatsheet – The.Swift.Dev.

I’ve briefly mentioned the utilization of the Charts API in this post. For this tutorial, let’s see learn how to use the APIs to create a line chart.

The Climate Information

To show the SwiftUI Charts API, we are going to create a line chart that shows the typical temperature of Hong Kong, Taipei, and London from 2021-Jul to 2022-Jun.

To retailer the climate information, I created a WeatherData struct like under:

struct WeatherData: Identifiable

   let id = UUID()

   let date: Date

   let temperature: Double

 

   init(yr: Int, month: Int, day: Int, temperature: Double)

       self.date = Calendar.present.date(from: .init(yr: yr, month: month, day: day)) ?? Date()

       self.temperature = temperature

   

The Chart initializer takes in an inventory of Identifiable objects. This is the reason we make the WeatherData conform the Identifiable protocol.

For every metropolis, we create an array to retailer the climate information. Right here is an instance for London:

let londonWeatherData = [ WeatherData(year: 2021, month: 7, day: 1, temperature: 19.0),

                          WeatherData(year: 2021, month: 8, day: 1, temperature: 17.0),

                          WeatherData(year: 2021, month: 9, day: 1, temperature: 17.0),

                          WeatherData(year: 2021, month: 10, day: 1, temperature: 13.0),

                          WeatherData(year: 2021, month: 11, day: 1, temperature: 8.0),

                          WeatherData(year: 2021, month: 12, day: 1, temperature: 8.0),

                          WeatherData(year: 2022, month: 1, day: 1, temperature: 5.0),

                          WeatherData(year: 2022, month: 2, day: 1, temperature: 8.0),

                          WeatherData(year: 2022, month: 3, day: 1, temperature: 9.0),

                          WeatherData(year: 2022, month: 4, day: 1, temperature: 11.0),

                          WeatherData(year: 2022, month: 5, day: 1, temperature: 15.0),

                          WeatherData(year: 2022, month: 6, day: 1, temperature: 18.0)

]

To retailer the climate information of the cities, we even have an array for that:

let chartData = [ (city: “Hong Kong”, data: hkWeatherData),

                  (city: “London”, data: londonWeatherData),

                  (city: “Taipei”, data: taipeiWeatherData) ]

Making a Easy Line Chart Utilizing Chart and LineMark

To create any sorts of chart utilizing the Charts framework, you must first import the Chartsframework:

Subsequent, you begin with the Chart view. Contained in the Chart view, you present a set of LineMark to create a line chart. Right here is an instance:

struct SimpleLineChartView: View {

    var physique: some View

        VStack

            Chart

                ForEach(hkWeatherData) merchandise in

                    LineMark(

                        x: .worth(“Month”, merchandise.date),

                        y: .worth(“Temp”, merchandise.temperature)

                    )

                

            

            .body(top: 300)

        

    

}

What the code above does is to plot a line chart for displaying the typical temperature of Hong Kong. The ForEach assertion loops by way of all objects saved in hkWeatherData. For every merchandise, we create a LineMark object that the x axis is ready to the date and the y axis is ready to the typical temperature.

Optionally, you possibly can resize the chart utilizing the body modifier. When you preview the code in Xcode preview, it’s best to see the next line chart:

swiftui-line-chart-simple

Customizing Chart Axes

You’ll be able to customise each x and y axes through the use of the chartXAxis and chartYAxis modifiers respectively. Let’s say, if we wish to show the month labels utilizing the digit format, we are able to connect the chartXAxis modifier to the Chart view like this:

.chartXAxis

    AxisMarks(values: .stride(by: .month)) worth in

        AxisGridLine()

        AxisValueLabel(format: .dateTime.month(.defaultDigits))    

    

Inside chartXAxis , we create a visible mark known as AxisMarks for the values of month. For every worth, we show a worth label through the use of a selected format. This line of code tells SwiftUI chart to make use of the digit format:

.dateTime.month(.defaultDigits)

On prime of that, we added some grid strains through the use of AxisGridLine.

For the y-axis, as an alternative of show the axis on the trailing (or proper) facet, we wish to swap it to the main (or left) facet. To do this, connect the chartYAxis modifier like this:

.chartYAxis

    AxisMarks(place: .main)

When you’ve made the change, Xcode preview ought to replace the chart like under. The y-axis is moved to the left facet and the format of month is modified. Plus, it’s best to see some grid strains.

swiftui-charts-changing-axis

Customizing the Background Shade of the Plot Space

The chartPlotStyle modifier permits you to change the background colour of the plot space. Connect the modifier to the Chart view like this:

.chartPlotStyle plotArea in

    plotArea

        .background(.blue.opacity(0.1))

We will then change the plot space utilizing the background modifier. For instance, we modify the plot space to mild blue.

swiftui-line-chart-background

Making a Multi-line Chart

Now the chart shows a single supply of information (i.e. the climate information of Hong Kong), so how can we show the climate information of London and Taipei in the identical line chart?

You’ll be able to rewrite the code of Chart view like this:

Chart

    ForEach(chartData, id: .metropolis) sequence in

        ForEach(sequence.information) merchandise in

            LineMark(

                x: .worth(“Month”, merchandise.date),

                y: .worth(“Temp”, merchandise.temperature)

            )

        

        .foregroundStyle(by: .worth(“Metropolis”, sequence.metropolis))

    

We’ve one other ForEach to loop by way of all of the cities of the chart information. Right here, the foregroundStyle modifier is used to use a special colour for every line. You don’t must specify the colour. SwiftUI will routinely choose the colour for you.

swiftui-multi-line-chart

Proper now, all of the cities share the identical image. If you wish to use a definite image, place the next line of code after foregroundStyle:

.image(by: .worth(“Metropolis”, sequence.metropolis))

Now every metropolis has its personal image within the line chart.

swiftui-line-chart-symbol

Customizing the Interpolation Methodology

You’ll be able to alter the interpolation technique of the road chart by attaching the interpolationMethod modifier to LineMark. Right here is an instance:

.interpolationMethod(.stepStart)

When you change the interpolation technique to .stepStart, the road chart now appears to be like like this:

swiftui-chart-interpolation-method

Apart from .stepStart, you possibly can check out the next choices:

  • cardinal
  • catmullRom
  • linear
  • monotone
  • stepCenter
  • stepEnd

Abstract

The Charts framework is a superb addition to SwiftUI. Even in case you simply start studying SwiftUI, you possibly can create pleasant charts with a number of strains of code. Whereas this tutorial focuses on line charts, the Charts API makes it very simple for builders to transform the chart to different varieties akin to bar chart. You’ll be able to take a look at the Swift Charts documentation for additional studying.

Notice: We’re updating our Mastering SwiftUI book for iOS 16. If you wish to begin studying SwiftUI, take a look at the e book here. You’ll obtain a free replace later this yr.





Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

The abstract Vapor service factory design pattern

by learningcode_x1mckf
February 1, 2023
0
The abstract Vapor service factory design pattern

I've written a number of articles about manufacturing unit design patterns on my weblog and this time I might like to speak a couple of particular one, which...

Read more

SwiftNIO tutorial – The echo server

by learningcode_x1mckf
January 27, 2023
0
SwiftNIO tutorial – The echo server

Intoducing SwiftNIO In the event you used a excessive degree net framework, corresponding to Vapor, up to now, you would possibly had some interplay with occasion loops...

Read more

Introducing – Vapor cheatsheet – The.Swift.Dev.

by learningcode_x1mckf
January 23, 2023
0
Introducing – Vapor cheatsheet – The.Swift.Dev.

Out there on Gumroad Thanks for supporting my work by buying the cheatsheet. 🙏 Download now A whole Vapor framework reference for novices. greater than...

Read more

iCloud Programming Tutorial for iOS: An Introduction

by learningcode_x1mckf
January 18, 2023
0
iCloud Programming Tutorial for iOS: An Introduction

Editor’s observe: This week, we work with Ziad Tamim once more to provide you an introduction of iCloud programming. You’ll learn to save and retrieve knowledge from iCloud.On...

Read more

Easy multipart file upload for Swift

by learningcode_x1mckf
January 18, 2023
0
Easy multipart file upload for Swift

I imagine that you've got already heard in regards to the well-known multipart-data add method that everybody likes to add recordsdata and submit type knowledge, but when not,...

Read more
Next Post
Time limit for notify – JavaScript – SitePoint Forums

Multiple select that could work on my select - JavaScript - SitePoint Forums

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Azul on helping Filipino customers run Java apps efficiently – Manila Bulletin

Azul on helping Filipino customers run Java apps efficiently – Manila Bulletin

September 23, 2022
Java Burn Reviews – Effective Ingredients for Weight Loss or Bogus Claims

Java Burn Reviews – Effective Ingredients for Weight Loss or Bogus Claims

September 29, 2022
Java Developer(eTrading) (JHB/CPT/KZN) at Datafin Recruitment

Java Developer(eTrading) (JHB/CPT/KZN) at Datafin Recruitment

October 20, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • C++ Is TIOBE's Language Of The Year – iProgrammer
  • JobRunr, the Java Scheduler Library, Released Version 6.0 – InfoQ.com
  • An Introduction to Lodash and Its Benefits for JavaScript Developers – MUO – MakeUseOf

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?