简体   繁体   中英

Starting and Ending Values for Swift Chart

I am trying to build a Line Chart View using Swift charts in SwiftUI. I have x values from 0 to 23, and random y values between 30 and 40, however the plot is covering the whole screen and I just need the portion from 30 to 40 on the y-axis. What should I do? The code:

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()
    }
}

You would need to add the following modifier at the end of your chart view:

.chartYScale(domain: 30.0…40.0)

Here is the full code along with some changes.


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()
    }
} ```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM