Created
August 4, 2025 08:27
-
-
Save adriansergheev/8b98f684713c4a46f59044be2e54a71e to your computer and use it in GitHub Desktop.
quarter-hour-charts-swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import SwiftUI | |
| import Charts | |
| struct EnergyReading { | |
| let timestamp: Date | |
| let kWh: Double | |
| } | |
| struct EnergyBarChartView: View { | |
| @State private var energyData: [EnergyReading] = { | |
| let calendar = Calendar.current | |
| let startTime = calendar.startOfDay(for: calendar.date(byAdding: .day, value: -1, to: Date())!) | |
| let result = (0..<24).map { intervalIndex in | |
| let timestamp = calendar.date(byAdding: .minute, value: intervalIndex * 15, to: startTime)! | |
| let kWh = Double.random(in: 0.5...4.8) | |
| return EnergyReading(timestamp: timestamp, kWh: kWh) | |
| } | |
| print(result) | |
| return result | |
| }() | |
| var body: some View { | |
| VStack(alignment: .leading, spacing: 16) { | |
| Text("Energy Consumption") | |
| .font(.title2) | |
| .fontWeight(.semibold) | |
| Chart(energyData, id: \.timestamp) { reading in | |
| BarMark( | |
| x: .value("Time", reading.timestamp), | |
| y: .value("Energy (kWh)", reading.kWh), | |
| // width: .ratio(0.75) // does not work | |
| width: .automatic // works | |
| ) | |
| .foregroundStyle(.blue.gradient) | |
| } | |
| .chartXAxis { | |
| AxisMarks(values: .stride(by: .hour, count: 1)) { value in | |
| if let date = value.as(Date.self) { | |
| AxisGridLine() | |
| AxisTick() | |
| AxisValueLabel { | |
| Text(date, format: .dateTime.hour(.defaultDigits(amPM: .abbreviated))) | |
| } | |
| } | |
| } | |
| } | |
| .chartYAxis { | |
| AxisMarks(values: .stride(by: 1.0)) { value in | |
| AxisGridLine() | |
| AxisTick() | |
| AxisValueLabel { | |
| if let kWh = value.as(Double.self) { | |
| Text("\(kWh, specifier: "%.0f")") | |
| } | |
| } | |
| } | |
| } | |
| .chartYScale(domain: 0...5) | |
| .chartXScale(domain: .automatic(includesZero: false)) | |
| .frame(height: 300) | |
| Text("15-minute intervals showing energy consumption in kWh") | |
| .font(.caption) | |
| .foregroundColor(.secondary) | |
| } | |
| .padding() | |
| } | |
| } | |
| #Preview { | |
| ScrollView { | |
| EnergyBarChartView() | |
| } | |
| } |
Author
adriansergheev
commented
Aug 4, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment