Repository Public
1import Foundation2import SheetCore3import Statistics4import SheetCharts5import AnalysisKit67/// Frequency histogram of one numeric column.8enum HistogramTool {9 static let descriptor: ToolDescriptor = {10 var t = ToolDescriptor(11 id: "describe.histogram", title: L("Frequency Histogram"), group: Common.groupDescribe, systemImage: "chart.bar",12 summary: L("Frequency table and histogram of one numeric column over equal-width bins."),13 fields: [14 .range("data", L("Data range")),15 .column("x", L("Variable")),16 .choice("rule", L("Bin rule"), [17 FieldOption("auto", L("Automatic (larger of Sturges and Freedman–Diaconis)")), FieldOption("sturges", L("Sturges")),18 FieldOption("scott", L("Scott")), FieldOption("fd", L("Freedman–Diaconis")), FieldOption("fixed", L("Fixed number of bins")),19 ]),20 .integer("bins", L("Number of bins"), 10, min: 1, max: 500, visible: { $0.choice("rule") == "fixed" }),21 ],22 info: [23 L("Bins have equal width and span the minimum to the maximum; every bin is closed on the left and the last bin is also closed on the right (NumPy convention)."),24 L("Sturges: ⌈log₂ n⌉ + 1 bins. Scott: width 3.49·s·n^(−1/3). Freedman–Diaconis: width 2·IQR·n^(−1/3)."),25 L("Blank cells, text and error values are treated as missing."),26 ],27 run: run)28 t.demo = { _, v in v.set("data", range: "Regression!A1:G121"); v.set("x", column: 0) }29 return t30 }()3132 /// Number of equal-width bins given by a rule ("auto", "sturges", "scott", "fd"; anything else → `fixed`).33 static func binCount(_ x: [Double], rule: String, fixed: Int) -> Int {34 let n = Double(x.count)35 guard x.count > 1, let lo = x.min(), let hi = x.max(), hi > lo else { return 1 }36 let sturges = Int(ceil(log2(n))) + 137 func fromWidth(_ w: Double) -> Int { w > 0 && w.isFinite ? min(max(Int(ceil((hi - lo) / w)), 1), 500) : sturges }38 switch rule {39 case "sturges": return sturges40 case "scott": return fromWidth(3.49 * Descriptive.standardDeviation(x) * pow(n, -1.0 / 3))41 case "fd": return fromWidth(2 * Descriptive.interquartileRange(x) * pow(n, -1.0 / 3))42 case "auto": return max(sturges, fromWidth(2 * Descriptive.interquartileRange(x) * pow(n, -1.0 / 3)))43 default: return min(max(fixed, 1), 500)44 }45 }4647 static func run(_ input: ToolInput) throws -> ToolResult {48 let frame = try input.frame()49 let col = try input.column("x")50 let x = col.present51 guard !x.isEmpty else { throw ToolError(L("The column “%@” contains no numbers.", col.name)) }52 let bins = binCount(x, rule: input.values.choice("rule"), fixed: input.values.int("bins"))53 let h = Descriptive.histogram(x, binCount: bins)54 let n = Double(x.count)55 var rows: [[Value]] = [[.text(L("Bin")), .text(L("From")), .text(L("To")), .text(L("Frequency")), .text(L("Relative frequency")),56 .text(L("Cumulative frequency")), .text(L("Cumulative relative frequency"))]]57 var cumulative = 058 for (i, c) in h.counts.enumerated() {59 cumulative += c60 rows.append([.number(Double(i + 1)), .number(h.edges[i]), .number(h.edges[i + 1]), .number(Double(c)), .number(Double(c) / n),61 .number(Double(cumulative)), .number(Double(cumulative) / n)])62 }63 let table = ReportTable(title: L("Frequency table"), rows: rows, headerColumn: false,64 columnFormats: [0: .integer, 3: .integer, 4: .percent(1), 5: .integer, 6: .percent(1)])65 let modal = h.counts.enumerated().max { $0.element < $1.element }?.offset ?? 066 // bin mid-points as axis labels, with just enough decimals for the bin width67 let width = h.edges[1] - h.edges[0]68 let decimals = width >= 10 ? 0 : (width >= 1 ? 1 : (width >= 0.1 ? 2 : 4))69 var spec = ChartKit.binned(edges: h.edges, counts: h.counts, xTitle: col.name, yTitle: L("Frequency"))70 spec.categories = .labels(zip(h.edges, h.edges.dropFirst()).map { Fmt.fixed(($0 + $1) / 2, decimals, locale: input.locale) })71 let chart = ChartBlock(title: L("Histogram of %@", col.name), spec: spec,72 summary: L("Histogram of %@ with %d bins of width %@; the fullest bin runs from %@ to %@ and holds %d of %d values.", col.name, bins,73 Fmt.number(h.edges[1] - h.edges[0], locale: input.locale), Fmt.number(h.edges[modal], locale: input.locale),74 Fmt.number(h.edges[modal + 1], locale: input.locale), h.counts[modal], x.count))75 var blocks: [ResultBlock] = [76 .metrics([Metric(L("Observations"), n, .integer), Metric(L("Bins"), Double(bins), .integer),77 Metric(L("Bin width"), h.edges[1] - h.edges[0]), Metric(L("Minimum"), x.min() ?? .nan), Metric(L("Maximum"), x.max() ?? .nan)]),78 .chart(chart), .table(table),79 ]80 if let note = Common.missingNote([col]) { blocks.append(.note([note])) }81 return ToolResult(title: L("Frequency Histogram"), subtitle: frame.label + " — " + col.name, blocks: blocks, sheetName: L("Histogram"))82 }83}84