Swift图表的起始值和结束值

pcww981p  于 2022-12-17  发布在  Swift
关注(0)|答案(1)|浏览(140)

我正在尝试建立一个线图视图使用SwiftUI中的Swift图表。我有x值从0到23,和随机y值30和40之间,但图是覆盖整个屏幕,我只需要从30到40的y轴上的部分。我该怎么办?代码:

struct PatientData: Decodable, Encodable, Identifiable  {
    var id: Int?
    
    let temperature: Double
    let timestamp: Int
    init(id: Int, temperature: Double, timestamp: Int) {
        self.id = id
        self.temperature = temperature
        self.timestamp = timestamp
    }
}

func generateData() -> [PatientData]{
    var data: [PatientData] = []
    for i in 0...23 {
        data.append(
            PatientData(id: i, temperature: Double.random(in: 30.0...40.0), timestamp: i)
        )
    }
    return data
}

struct TemperatureChartView: View {
    var data = generateData()
    var body: some View {
        Chart (data){
            LineMark(x: .value("Time", $0.timestamp), y: .value("Temperature", $0.temperature))
        }
    }
}

struct TemperatureChartView_Previews: PreviewProvider {
    static var previews: some View {
        TemperatureChartView()
    }
}
zbdgwd5y

zbdgwd5y1#

您需要在图表视图的末尾添加以下修饰符:
.chartYScale(domain: 30.0…40.0)
下面是完整的代码沿着一些更改。

struct PatientData: Identifiable, Codable {
    var id: Int
    let temperature: Double
    let timestamp: Int
    
    static func generateData() -> [PatientData] {
        (0...23).map { PatientData(id: $0, temperature: Double.random(in: 30.0...40.0), timestamp: $0) }
    }
}

struct TemperatureChartView: View {
    var data = PatientData.generateData()
    var body: some View {
        Chart(data) {
            LineMark(x: .value("Time", $0.timestamp), y: .value("Temperature", $0.temperature))
        }
        // Here
        .chartYScale(domain: 30.0...40.00)
        .padding()
    }
}

struct TemperatureChartView_Previews: PreviewProvider {
    static var previews: some View {
        TemperatureChartView()
    }
} ```

相关问题