Commit 6b184db05d

6b184db05d104f9845df4b2c6c069509ac8a2c8e

parent: fb82a26f74

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 10:14 UTC

Refuse log ranges at or below 0 and over 1000 radar rings without gnuplot, and draw log bars from the axis foot

Layout: unified · split

Sources/OrgApp/PlotChart.swift +36 −12
@@ -64,10 +64,13 @@ public struct PlotChart: View {
64 let ticks = o["ticks"].flatMap { if case .number(let n) = $0 { Int(n) } else { nil } } 64 let ticks = o["ticks"].flatMap { if case .number(let n) = $0 { Int(n) } else { nil } }
65 let numericX = series.allSatisfy { $0.points.allSatisfy { if case .number = $0.x { true } else { false } } } 65 let numericX = series.allSatisfy { $0.points.allSatisfy { if case .number = $0.x { true } else { false } } }
66 let bars = ["boxes", "histograms", "hist", "impulses"].contains(o.with) 66 let bars = ["boxes", "histograms", "hist", "impulses"].contains(o.with)
67 let yGiven = (low: s.yrange?.low ?? PlotChart.number(o["ymin"]), high: s.yrange?.high ?? PlotChart.number(o["ymax"]))
68 // A log axis has no 0, so bars stand on its foot, the range the SVG gives it.
69 let logBars = bars && s.logY ? try? TablePlot.Axis(values: ys, given: yGiven.low == nil && yGiven.high == nil ? nil : .init(low: yGiven.low, high: yGiven.high), log: true, step: nil, zero: false) : nil
67 let chart = Chart { 70 let chart = Chart {
68 ForEach(Array(series.enumerated()), id: \.offset) { _, s in 71 ForEach(Array(series.enumerated()), id: \.offset) { _, s in
69 ForEach(Array(s.points.enumerated()), id: \.offset) { _, point in 72 ForEach(Array(s.points.enumerated()), id: \.offset) { _, point in
70 mark(point.x, point.y, series: s.label) 73 mark(point.x, point.y, base: logBars?.low, series: s.label)
71 } 74 }
72 } 75 }
73 } 76 }
@@ -91,7 +94,9 @@ public struct PlotChart: View {
91 // As gnuplot autoscales: to the data, from zero for bars. 94 // As gnuplot autoscales: to the data, from zero for bars.
92 let yType: ScaleType? = s.logY ? .log : nil, xType: ScaleType? = s.logX ? .log : nil 95 let yType: ScaleType? = s.logY ? .log : nil, xType: ScaleType? = s.logX ? .log : nil
93 let y = Group { 96 let y = Group {
94 if let domain = PlotChart.domain(s.yrange?.low ?? PlotChart.number(o["ymin"]), s.yrange?.high ?? PlotChart.number(o["ymax"]), values: ys) { 97 if let logBars {
98 chart.chartYScale(domain: logBars.low...logBars.high, type: yType)
99 } else if let domain = PlotChart.domain(yGiven.low, yGiven.high, values: ys) {
95 chart.chartYScale(domain: domain, type: yType) 100 chart.chartYScale(domain: domain, type: yType)
96 } else { 101 } else {
97 chart.chartYScale(domain: .automatic(includesZero: bars && !s.logY), type: yType) 102 chart.chartYScale(domain: .automatic(includesZero: bars && !s.logY), type: yType)
@@ -107,25 +112,33 @@ public struct PlotChart: View {
107 } 112 }
108 113
109 @ChartContentBuilder 114 @ChartContentBuilder
110 func mark(_ x: TablePlot.Series.X, _ y: Double, series: String) -> some ChartContent { 115 func mark(_ x: TablePlot.Series.X, _ y: Double, base: Double?, series: String) -> some ChartContent {
111 switch x { 116 switch x {
112 case .number(let n): marks(.value("x", n), y, series) 117 case .number(let n): marks(.value("x", n), y, base, series)
113 case .date(let d): marks(.value("x", d), y, series) 118 case .date(let d): marks(.value("x", d), y, base, series)
114 case .label(let l): marks(.value("x", l), y, series) 119 case .label(let l): marks(.value("x", l), y, base, series)
115 } 120 }
116 } 121 }
117 122
118 @ChartContentBuilder 123 @ChartContentBuilder
119 func marks<X: Plottable>(_ x: PlottableValue<X>, _ y: Double, _ series: String) -> some ChartContent { 124 func marks<X: Plottable>(_ x: PlottableValue<X>, _ y: Double, _ base: Double?, _ series: String) -> some ChartContent {
120 switch plot.options.with { 125 switch plot.options.with {
121 case "points", "dots": 126 case "points", "dots":
122 PointMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)) 127 PointMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series))
123 case "linespoints": 128 case "linespoints":
124 LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).symbol(by: .value("Series", series)) 129 LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).symbol(by: .value("Series", series))
125 case "impulses": 130 case "impulses":
126 BarMark(x: x, y: .value("y", y), width: 2).foregroundStyle(by: .value("Series", series)) 131 if let base {
132 BarMark(x: x, yStart: .value("y", base), yEnd: .value("y", y), width: 2).foregroundStyle(by: .value("Series", series))
133 } else {
134 BarMark(x: x, y: .value("y", y), width: 2).foregroundStyle(by: .value("Series", series))
135 }
127 case "boxes", "histograms", "hist": 136 case "boxes", "histograms", "hist":
128 BarMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).position(by: .value("Series", series)) 137 if let base {
138 BarMark(x: x, yStart: .value("y", base), yEnd: .value("y", y)).foregroundStyle(by: .value("Series", series)).position(by: .value("Series", series))
139 } else {
140 BarMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).position(by: .value("Series", series))
141 }
129 case "steps": 142 case "steps":
130 LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).interpolationMethod(.stepEnd) 143 LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).interpolationMethod(.stepEnd)
131 case "fsteps": 144 case "fsteps":
@@ -361,10 +374,21 @@ public enum PlotOutput {
361 } 374 }
362 375
363 /// Refuses what the chart can't draw: a radar plot `TablePlot.radar` refuses, which 376 /// Refuses what the chart can't draw: a radar plot `TablePlot.radar` refuses, which
364 /// `TablePlot.plot` leaves to gnuplot when there's a `script:`. 377 /// `TablePlot.plot` leaves to gnuplot when there's a `script:`, or one with more than 1000
378 /// rings, and a log axis the SVG refuses, which Swift Charts traps on.
365 public static func check(_ plot: TablePlot.Plot) throws { 379 public static func check(_ plot: TablePlot.Plot) throws {
366 guard plot.options.type == "radar" else { return } 380 switch plot.options.type {
367 do { _ = try TablePlot.radar(plot) } catch { throw Failure(description: "\(error)") } 381 case "radar":
382 let radar: TablePlot.Radar
383 do { radar = try TablePlot.radar(plot) } catch { throw Failure(description: "\(error)") }
384 guard radar.ticks <= 1000 else { throw Failure(description: "Without gnuplot, ticks: takes 0 to 1000") }
385 case "2d":
386 let s = TablePlot.settings(plot)
387 guard s.logX || s.logY else { return }
388 do { _ = try TablePlot.svg(plot) } catch { throw Failure(description: "\(error)") }
389 default:
390 return
391 }
368 } 392 }
369 393
370 /// The chart as gnuplot's default 640×480, as PNG, JPEG, PDF or SVG by the file's extension. 394 /// The chart as gnuplot's default 640×480, as PNG, JPEG, PDF or SVG by the file's extension.
Sources/OrgCore/Compute/PlotSVG.swift +4 −4
@@ -13,13 +13,13 @@ extension TablePlot {
13 } 13 }
14 14
15 /// An axis: its ends, widened to whole steps where they're not given, and its ticks. 15 /// An axis: its ends, widened to whole steps where they're not given, and its ticks.
16 struct Axis { 16 public struct Axis {
17 var low: Double 17 public var low: Double
18 var high: Double 18 public var high: Double
19 var log: Bool 19 var log: Bool
20 var ticks: [Double] = [] 20 var ticks: [Double] = []
21 21
22 init(values: [Double], given: Settings.Range?, log: Bool, step: Double?, zero: Bool) throws { 22 public init(values: [Double], given: Settings.Range?, log: Bool, step: Double?, zero: Bool) throws {
23 var data = values.filter { !log || $0 > 0 } 23 var data = values.filter { !log || $0 > 0 }
24 // gnuplot refuses these too. 24 // gnuplot refuses these too.
25 if log, data.isEmpty, given?.low == nil || given?.high == nil { throw Failure(description: "A log axis needs values above 0") } 25 if log, data.isEmpty, given?.low == nil || given?.high == nil { throw Failure(description: "A log axis needs values above 0") }
Sources/OrgCore/Compute/PlotSettings.swift +5
@@ -12,6 +12,11 @@ extension TablePlot {
12 public struct Range: Sendable, Equatable { 12 public struct Range: Sendable, Equatable {
13 public var low: Double? 13 public var low: Double?
14 public var high: Double? 14 public var high: Double?
15
16 public init(low: Double?, high: Double?) {
17 self.low = low
18 self.high = high
19 }
15 } 20 }
16 21
17 public var title: String? 22 public var title: String?
Tests/OrgAppTests/PlotChartTests.swift +31
@@ -105,6 +105,37 @@ struct PlotChartTests {
105 try PlotOutput.check(plot) 105 try PlotOutput.check(plot)
106 } 106 }
107 107
108 @Test func refusesLogRangesAndDrawsLogBars() throws {
109 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-log-\(UUID().uuidString)")
110 defer { try? FileManager.default.removeItem(at: folder) }
111 let data = "| 1 | 3 |\n| 2 | 4 |\n"
112 for options in ["set:\"logscale y\" set:\"yrange [0:100]\"", "set:\"logscale x\" set:\"xrange [0:10]\"",
113 "set:\"logscale y\" set:\"yrange [-1:100]\"", "set:\"logscale y\" ymin:0", "set:\"logscale x\" xmin:-1"] {
114 let plot = try Self.plot("#+PLOT: ind:1 \(options)\n" + data)
115 #expect(throws: PlotOutput.Failure.self, "\(options)") { try PlotOutput.check(plot) }
116 for name in ["o.png", "o.pdf"] {
117 #expect(throws: PlotOutput.Failure.self, "\(options)") { try PlotOutput.write(plot, to: folder.appendingPathComponent(name)) }
118 }
119 }
120 for options in ["with:boxes set:\"logscale y\"", "with:impulses set:\"logscale y\"", "with:histograms set:\"logscale y\"",
121 "with:boxes set:\"logscale y\" set:\"yrange [0.5:10]\"", "with:impulses set:\"logscale y\" set:\"yrange [2:10]\"", "with:boxes set:\"logscale xy\"", "with:lines set:\"logscale y\""] {
122 let plot = try Self.plot("#+PLOT: ind:1 \(options)\n| 1 | 1 |\n| 2 | 5 |\n")
123 for name in ["b.png", "b.pdf"] {
124 let url = folder.appendingPathComponent(name)
125 try PlotOutput.write(plot, to: url)
126 let size = (try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0
127 #expect(size > 1000, "\(options) \(name) is \(size) bytes")
128 }
129 }
130 }
131
132 @Test func capsRadarRingsWithoutGnuplot() throws {
133 let plot = try Self.plot("#+PLOT: type:radar ticks:2000\n| n | a | b |\n|---+---+---|\n| x | 1 | 5 |\n| y | 2 | 3 |\n")
134 #expect(try TablePlot.radarSetup(plot).hasSuffix(" 2000\nEOD\n"))
135 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.check(plot) }
136 try PlotOutput.check(Self.plot("#+PLOT: type:radar ticks:1000\n| n | a | b |\n|---+---+---|\n| x | 1 | 5 |\n| y | 2 | 3 |\n"))
137 }
138
108 @Test func writesSVG() throws { 139 @Test func writesSVG() throws {
109 let lines = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"title 'T&C'\" set:\"xlabel 'Day'\" set:\"grid\"\n" + Self.table)) 140 let lines = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"title 'T&C'\" set:\"xlabel 'Day'\" set:\"grid\"\n" + Self.table))
110 #expect(lines.hasPrefix("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"480\"")) 141 #expect(lines.hasPrefix("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"480\""))