LoginSignup
0
1

【Swift】Chartsを使って折れ線グラフを表示する方法

Posted at

はじめに

備忘録
タイトルの通りです。
どなたかのお役に立てれば幸いです。

解決方法

ChartsiOS 16からサポートされています。

使用するにはChartsをインポートする必要があります。

import Charts

以下のように使います。
LineMarkは折れ線グラフを表示します。
PointMarkはデータがあるところにプロットします。
これら2つを組み合わせることで、プロットした点同士を結んだ折れ線グラフを表示することができます。

struct ContentView: View {
    let data = [  // サンプルデータの作成
        Data(time: 1, voltage: 100),
        Data(time: 2, voltage: 200),
        Data(time: 3, voltage: 300),
    ]

    var body: some View {
        Chart {
            ForEach(data) { datum in
                LineMark(x: .value("Time", datum.time),
                         y: .value("Voltage", datum.voltage))
                PointMark(x: .value("Time", datum.time),
                          y: .value("Voltage", datum.voltage))
                .foregroundStyle(.green)  // 色を変えることもできるし
                .opacity(0.5)             // 透明度を変えることもできる
            }
        }
        .chartYAxis {
            AxisMarks(position: .leading)  // たて軸を左側に表示
        }
        .chartXAxisLabel(position: .bottom, alignment: .center) {
            Text("Time [s]")
        }  // 軸ラベルをグラフの下側の左右中心に表示
        .chartYAxisLabel(position: .leading, alignment: .center, spacing: 0) {
            Text("Voltage [mV]")
        }  // 軸ラベルをグラフの左側の上下中央に表示し、周りの要素とのスペースをなくす
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1