SPB Git

Repository Public

ChartKit.swift 6.4 KB 117 lines swift

1import Foundation2import SheetCore3import SheetCharts45/// Builders for the result charts of the studios. Every spec uses literal data (`DataRef.literal`), so it can be6/// drawn in a panel as is and bound to sheet cells by `ChartBinder` when inserted into the workbook.7public enum ChartKit {8    public struct Line: Sendable {9        public var name: String10        public var values: [Double]11        public var x: [Double]?12        public var lower: [Double]?13        public var upper: [Double]?14        public var dash: LineDash15        public var marker: MarkerShape16        public init(_ name: String, _ values: [Double], x: [Double]? = nil, lower: [Double]? = nil, upper: [Double]? = nil,17                    dash: LineDash = .solid, marker: MarkerShape = .none) {18            self.name = name; self.values = values; self.x = x; self.lower = lower; self.upper = upper; self.dash = dash; self.marker = marker19        }20    }2122    static func base(_ kind: ChartKind, xTitle: String, yTitle: String, yFormat: String = "", xFormat: String = "") -> ChartSpec {23        var spec = ChartSpec(kind: kind)24        spec.xAxis.title = xTitle; spec.yAxis.title = yTitle25        spec.yAxis.numberFormat = yFormat; spec.xAxis.numberFormat = xFormat26        return spec27    }2829    /// Frequency histogram of a sample.30    public static func histogram(_ values: [Double], xTitle: String, yTitle: String, rule: BinRule = .auto, binCount: Int = 10) -> ChartSpec {31        var spec = base(.histogram, xTitle: xTitle, yTitle: yTitle)32        spec.series = [SeriesSpec(name: xTitle, values: .literal(values))]33        spec.options.binRule = rule34        spec.options.binCount = binCount35        return spec36    }3738    /// Histogram from precomputed equal-width bins (`edges.count == counts.count + 1`).39    public static func binned(edges: [Double], counts: [Int], xTitle: String, yTitle: String) -> ChartSpec {40        var spec = base(.column, xTitle: xTitle, yTitle: yTitle)41        let mids = zip(edges, edges.dropFirst()).map { ($0 + $1) / 2 }42        spec.categories = .labels(mids.map { Fmt.number($0) })43        spec.series = [SeriesSpec(name: yTitle, values: .literal(counts.map(Double.init)))]44        spec.options.barGap = 0.0445        spec.xAxis.gridlines = false46        return spec47    }4849    /// Lines over a numeric x (each line may bring its own x), or over 1…n when no x is given. Bands from lower/upper.50    public static func lines(_ lines: [Line], xTitle: String, yTitle: String, yFormat: String = "", dateAxis: Bool = false) -> ChartSpec {51        var spec = base(dateAxis ? .timeSeries : .line, xTitle: xTitle, yTitle: yTitle, yFormat: yFormat)52        spec.series = lines.map { l in53            let x = l.x ?? (0..<l.values.count).map { Double($0 + 1) }54            return SeriesSpec(name: l.name, values: .literal(l.values), x: .literal(x), lower: l.lower.map { .literal($0) }, upper: l.upper.map { .literal($0) },55                              style: SeriesStyle(dash: l.dash, marker: l.marker))56        }57        if dateAxis { spec.xAxis.scale = .date }58        spec.legend = LegendSpec(position: lines.count > 1 ? .top : .none)59        return spec60    }6162    /// Scatter plot of one or more (x, y) clouds; optional horizontal / vertical reference lines.63    public static func scatter(_ series: [(name: String, x: [Double], y: [Double])], xTitle: String, yTitle: String,64                               horizontal: [Double] = [], vertical: [Double] = [], trend: Bool = false) -> ChartSpec {65        var spec = base(.scatter, xTitle: xTitle, yTitle: yTitle)66        spec.series = series.map { s in67            var ss = SeriesSpec(name: s.name, values: .literal(s.y), x: .literal(s.x), style: SeriesStyle(marker: .circle, markerSize: 4.5, fillOpacity: 0.75))68            if trend { ss.trendline = .linear() }69            return ss70        }71        spec.annotations = horizontal.map { .referenceLine(.horizontal, at: $0) } + vertical.map { .referenceLine(.vertical, at: $0) }72        spec.legend = LegendSpec(position: series.count > 1 ? .top : .none)73        return spec74    }7576    /// Vertical bars per category; `bounds` draws symmetric dashed reference lines (ACF / PACF significance limits).77    public static func columns(categories: [String], series: [(name: String, values: [Double])], xTitle: String, yTitle: String,78                               bounds: Double? = nil, yFormat: String = "") -> ChartSpec {79        var spec = base(.column, xTitle: xTitle, yTitle: yTitle, yFormat: yFormat)80        spec.categories = .labels(categories)81        spec.series = series.map { SeriesSpec(name: $0.name, values: .literal($0.values)) }82        spec.xAxis.gridlines = false83        if let b = bounds, b.isFinite { spec.annotations = [.referenceLine(.horizontal, at: b), .referenceLine(.horizontal, at: -b)] }84        spec.legend = LegendSpec(position: series.count > 1 ? .top : .none)85        return spec86    }8788    /// Horizontal bars, largest first as given.89    public static func bars(categories: [String], values: [Double], xTitle: String, name: String = "") -> ChartSpec {90        var spec = base(.bar, xTitle: "", yTitle: xTitle)91        spec.categories = .labels(categories)92        spec.series = [SeriesSpec(name: name.isEmpty ? xTitle : name, values: .literal(values))]93        spec.legend = LegendSpec(position: .none)94        return spec95    }9697    /// Tornado: for each input the change of the output at the low and at the high input value (relative to the base).98    public static func tornado(inputs: [String], deltaLow: [Double], deltaHigh: [Double], lowName: String, highName: String, valueTitle: String) -> ChartSpec {99        var spec = base(.bar, xTitle: "", yTitle: valueTitle)100        spec.categories = .labels(inputs)101        spec.series = [SeriesSpec(name: lowName, values: .literal(deltaLow)), SeriesSpec(name: highName, values: .literal(deltaHigh))]102        spec.options.stacking = .stacked103        // on a horizontal bar chart the value axis is the chart's y axis: a `.horizontal` line marks value 0104        spec.annotations = [.referenceLine(.horizontal, at: 0)]105        spec.legend = LegendSpec(position: .top)106        return spec107    }108109    /// Normal Q–Q plot data: theoretical quantiles (Blom positions) against the sorted sample.110    public static func normalQQ(_ sample: [Double]) -> (theoretical: [Double], ordered: [Double]) {111        let s = sample.filter(\.isFinite).sorted()112        let n = Double(s.count)113        let q = (0..<s.count).map { i in Statistics_normalQuantile((Double(i) + 1 - 0.375) / (n + 0.25)) }114        return (q, s)115    }116}117
Files main
Menu

Theme