Skip to content

Instantly share code, notes, and snippets.

@hishnash
Created September 3, 2026 10:04
Show Gist options
  • Select an option

  • Save hishnash/40f409f1d6fa4ad97aa1b5af8c1917bb to your computer and use it in GitHub Desktop.

Select an option

Save hishnash/40f409f1d6fa4ad97aa1b5af8c1917bb to your computer and use it in GitHub Desktop.
Sunburst Chart
import Algorithms
import Charts
import Foundation
import SwiftUI
// MARK: - Chart
extension ScreenTimeCategory: Plottable {}
struct ScreenTimeSunburst: View {
private let layout = ScreenTimeSunburstLayout(
aggregation: ScreenTimeAggregation(
records: screenTimeRecords
)
)
private let rings = RingMetrics.resolve(
levelCount: 3,
centerRadius: 0.32,
levelSpacing: 0.025
)
private let sectorCornerRadius: CGFloat = 1.5
var body: some View {
Chart {
// MARK: - Angular domain
// Preserve the full 0..<1 angular domain without drawing a sector.
// Otherwise, Charts stretches the inset ranges to fill the circle,
// closing the gap between the first and last sectors.
SectorMark(
angle: .value(
"Full angular domain",
0.0..<1.0
),
innerRadius: .ratio(0),
outerRadius: .ratio(0)
)
.foregroundStyle(.clear)
.accessibilityHidden(true)
// MARK: - Depth-first sectors
ForEach(layout.sectors) { sector in
let ring = rings[sector.ringLevel]
SectorMark(
angle: .value(
"Time",
sector.angularRange
),
innerRadius: .ratio(
ring.innerRadiusRelativeToOuter
),
outerRadius: .ratio(ring.outerRadius)
)
.cornerRadius(sectorCornerRadius)
.foregroundStyle(
by: .value("Category", sector.category)
)
.opacity([1.0, 0.78, 0.52][sector.ringLevel])
.accessibilityLabel(
sector.ringLevel == 0
? sector.name
: "\(sector.category.rawValue), \(sector.name)"
)
.accessibilityValue(hoursLabel(sector.hours))
}
// MARK: - Annotation anchors above the visible sectors
ForEach(layout.sectors) { sector in
let ring = rings[sector.ringLevel]
if sector.ringLevel == 0
|| (sector.ringLevel == 1 && sector.angularWidth > 0.055) {
SectorMark(
angle: .value(
"Label anchor",
sector.labelAnchorRange
),
innerRadius: .ratio(
ring.labelAnchor.innerRadiusRelativeToOuter
),
outerRadius: .ratio(
ring.labelAnchor.outerRadius
)
)
.opacity(0)
.annotation(position: .overlay) {
if sector.ringLevel == 0 {
Image(
systemName: sector.category.symbolName
)
.font(.headline)
.foregroundStyle(.white)
.accessibilityHidden(true)
} else {
Text(sector.name)
.font(.caption2.weight(.semibold))
.foregroundStyle(.white)
.shadow(
color: .black.opacity(0.5),
radius: 1
)
.multilineTextAlignment(.center)
.lineLimit(2)
.frame(maxWidth: 72)
.accessibilityHidden(true)
}
}
.accessibilityHidden(true)
}
}
}
.chartForegroundStyleScale(mapping: { (category: ScreenTimeCategory) in
color(for: category)
})
.chartLegend(.hidden)
.aspectRatio(1, contentMode: .fit)
.padding()
}
// MARK: - Styling
private func color(
for category: ScreenTimeCategory
) -> Color {
switch category {
case .productivity:
.indigo
case .social:
.pink
case .entertainment:
.purple
case .games:
.orange
case .readingAndLearning:
.green
case .creativity:
.teal
}
}
private func hoursLabel(_ hours: Double) -> String {
let value = hours.formatted(
.number.precision(.fractionLength(0...1))
)
return "\(value) hours"
}
}
// MARK: - Ring geometry
private struct RingMetrics {
let innerRadius: Double
let outerRadius: Double
var innerRadiusRelativeToOuter: Double {
innerRadius / outerRadius
}
var labelAnchor: RingMetrics {
let radius = (innerRadius + outerRadius) / 2
let halfThickness = 0.000_1
return RingMetrics(
innerRadius: radius - halfThickness,
outerRadius: radius + halfThickness
)
}
static func resolve(
levelCount: Int,
centerRadius: Double,
levelSpacing: Double
) -> [RingMetrics] {
let spacingTotal = levelSpacing * Double(levelCount - 1)
let levelWidth = (
1 - centerRadius - spacingTotal
) / Double(levelCount)
return (0..<levelCount).map { level in
let innerRadius = centerRadius
+ Double(level) * (levelWidth + levelSpacing)
return RingMetrics(
innerRadius: innerRadius,
outerRadius: innerRadius + levelWidth
)
}
}
}
// MARK: - Data aggregation
struct ScreenTimeAggregation: Sendable {
typealias Level = (name: String, hours: Double)
typealias MiddleLevel = (
level: Level,
details: [Level]
)
typealias TopLevel = (
level: Level,
middleLevels: [MiddleLevel]
)
let topLevels: [TopLevel]
init(records: [ScreenTimeRecord]) {
let sortedRecords = Self.sorted(records)
topLevels = Self.makeTopLevels(from: sortedRecords)
}
}
private extension ScreenTimeAggregation {
static func sorted(
_ records: [ScreenTimeRecord]
) -> [ScreenTimeRecord] {
records.sorted(using: [
KeyPathComparator(\.topLevel.rawValue),
KeyPathComparator(\.middleLevel),
KeyPathComparator(\.activity)
])
}
static func makeTopLevels(
from records: some Collection<ScreenTimeRecord>
) -> [TopLevel] {
records.chunked(on: \.topLevel).map { category, records in
(
level: (
name: category.rawValue,
hours: totalHours(in: records)
),
middleLevels: makeMiddleLevels(from: records)
)
}
}
static func makeMiddleLevels(
from records: some Collection<ScreenTimeRecord>
) -> [MiddleLevel] {
records.chunked(on: \.middleLevel).map { name, records in
(
level: (
name: name,
hours: totalHours(in: records)
),
details: makeDetails(from: records)
)
}
}
static func makeDetails(
from records: some Collection<ScreenTimeRecord>
) -> [Level] {
records.map { record in
(
name: record.activity,
hours: record.duration / 3_600
)
}
}
static func totalHours(
in records: some Collection<ScreenTimeRecord>
) -> Double {
records.reduce(0) { $0 + $1.duration } / 3_600
}
}
// MARK: - Angular layout
struct ScreenTimeSunburstLayout: Sendable {
struct Sector: Identifiable, Sendable {
let id: String
let name: String
let hours: Double
let ringLevel: Int
let startAngle: Double
let endAngle: Double
let category: ScreenTimeCategory
var angularRange: Range<Double> {
startAngle..<endAngle
}
var angularWidth: Double {
endAngle - startAngle
}
var labelAnchorRange: Range<Double> {
let midpoint = (startAngle + endAngle) / 2
let halfWidth = 0.000_1
return (midpoint - halfWidth)..<(midpoint + halfWidth)
}
}
let totalHours: Double
let sectors: [Sector]
init(aggregation: ScreenTimeAggregation) {
totalHours = aggregation.topLevels.reduce(0) {
$0 + $1.level.hours
}
// Append each parent immediately before its children.
var preparedSectors: [Sector] = []
let topLevelRanges = Self.allocate(
aggregation.topLevels.map(\.level),
within: 0.0..<1.0
)
for (topLevel, allocatedRange) in zip(
aggregation.topLevels,
topLevelRanges
) {
guard let category = ScreenTimeCategory(
rawValue: topLevel.level.name
) else {
continue
}
let plottedRange = Self.inset(
allocatedRange,
by: 0.006
)
let topSector = Sector(
id: category.rawValue,
name: topLevel.level.name,
hours: topLevel.level.hours,
ringLevel: 0,
startAngle: plottedRange.lowerBound,
endAngle: plottedRange.upperBound,
category: category
)
preparedSectors.append(topSector)
let middleLevelRanges = Self.allocate(
topLevel.middleLevels.map(\.level),
within: topSector.angularRange
)
for (middleLevel, allocatedRange) in zip(
topLevel.middleLevels,
middleLevelRanges
) {
let plottedRange = Self.inset(
allocatedRange,
by: 0.003
)
let middleSector = Sector(
id: "\(category.rawValue)/\(middleLevel.level.name)",
name: middleLevel.level.name,
hours: middleLevel.level.hours,
ringLevel: 1,
startAngle: plottedRange.lowerBound,
endAngle: plottedRange.upperBound,
category: category
)
preparedSectors.append(middleSector)
let detailRanges = Self.allocate(
middleLevel.details,
within: middleSector.angularRange
)
for (detail, allocatedRange) in zip(
middleLevel.details,
detailRanges
) {
let plottedRange = Self.inset(
allocatedRange,
by: 0.001_5
)
preparedSectors.append(
Sector(
id: "\(middleSector.id)/\(detail.name)",
name: detail.name,
hours: detail.hours,
ringLevel: 2,
startAngle: plottedRange.lowerBound,
endAngle: plottedRange.upperBound,
category: category
)
)
}
}
}
sectors = preparedSectors
}
private static func allocate(
_ levels: [ScreenTimeAggregation.Level],
within parentRange: Range<Double>
) -> [Range<Double>] {
let total = levels.reduce(0) { $0 + $1.hours }
guard total > 0 else { return [] }
let parentWidth = parentRange.upperBound
- parentRange.lowerBound
var boundaries = levels.reductions(
parentRange.lowerBound
) {
$0 + parentWidth * $1.hours / total
}
boundaries[boundaries.count - 1] = parentRange.upperBound
return boundaries.adjacentPairs().map {
$0..<$1
}
}
private static func inset(
_ range: Range<Double>,
by angularPadding: Double
) -> Range<Double> {
let width = range.upperBound - range.lowerBound
let inset = min(angularPadding / 2, width * 0.45)
return (range.lowerBound + inset)..<(range.upperBound - inset)
}
}
// MARK: - Preview
#Preview {
ScreenTimeSunburst()
.frame(width: 760, height: 940)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment