Native plots: set subset, radar, SVG !420

merged merged by cmc on 2026-11-21 14:08 UTC · krz/orgstar:parity-plots into main

12 files changed, +1105 −57

Layout: unified · split

Sources/OrgApp/PlotChart.swift +201 −30
@@ -5,7 +5,8 @@ import SwiftUI
5 5
6/// A `#+PLOT` table drawn by Swift Charts, as gnuplot would draw it for org-plot: 2d as lines, 6/// A `#+PLOT` table drawn by Swift Charts, as gnuplot would draw it for org-plot: 2d as lines,
7/// points, bars or impulses per `with:`, grid as a heat map, 3d as a surface (seen from above 7/// points, bars or impulses per `with:`, grid as a heat map, 3d as a surface (seen from above
8/// with `map:t`). `still` draws 3d as a wireframe, which an image can hold. 8/// with `map:t`), radar as a web. `still` draws 3d as a wireframe, which an image can hold.
9/// The `set` commands in `TablePlot.settings` are followed; the rest are left out.
9public struct PlotChart: View { 10public struct PlotChart: View {
10 let plot: TablePlot.Plot 11 let plot: TablePlot.Plot
11 let still: Bool 12 let still: Bool
@@ -16,85 +17,128 @@ public struct PlotChart: View {
16 } 17 }
17 18
18 public var body: some View { 19 public var body: some View {
20 let settings = TablePlot.settings(plot)
19 VStack(spacing: 8) { 21 VStack(spacing: 8) {
20 if let title = plot.options.title { Text(title).font(.headline) } 22 if let title = settings.title { Text(title).font(.headline) }
21 switch plot.options.type { 23 switch plot.options.type {
22 case "grid": HeatMap(plot: plot) 24 case "grid": HeatMap(plot: plot, settings: settings)
23 case "3d" where plot.options["map"]?.truthy == true: HeatMap(plot: plot) 25 case "3d" where plot.options["map"]?.truthy == true: HeatMap(plot: plot, settings: settings)
24 case "3d" where still: Wireframe(values: TablePlot.matrix(plot).values) 26 case "3d" where still: Wireframe(values: TablePlot.matrix(plot).values)
25 case "3d": Surface(plot: plot) 27 case "3d": Surface(plot: plot)
26 default: Lines(plot: plot) 28 case "radar": if let radar = try? TablePlot.radar(plot) { Radar(radar: radar) }
29 default: Lines(plot: plot, settings: settings)
27 } 30 }
28 } 31 }
29 .padding() 32 .padding()
30 } 33 }
31 34
32 /// The `ymin`/`ymax` (or `xmin`/`xmax`) range, filling in from `values` what isn't given. 35 /// The range given by `set` or the options, filling in from `values` what isn't given.
33 static func domain(_ low: TablePlot.Value?, _ high: TablePlot.Value?, values: [Double]) -> ClosedRange<Double>? { 36 static func domain(_ low: Double?, _ high: Double?, values: [Double]) -> ClosedRange<Double>? {
34 func number(_ v: TablePlot.Value?) -> Double? { if case .number(let n)? = v { n } else { nil } } 37 guard low != nil || high != nil else { return nil }
35 guard number(low) != nil || number(high) != nil else { return nil } 38 let lower = low ?? values.min() ?? 0
36 let lower = number(low) ?? values.min() ?? 0 39 let upper = high ?? values.max() ?? lower + 1
37 let upper = number(high) ?? values.max() ?? lower + 1
38 return lower < upper ? lower...upper : nil 40 return lower < upper ? lower...upper : nil
39 } 41 }
40 42
43 static func number(_ v: TablePlot.Value?) -> Double? { if case .number(let n)? = v { n } else { nil } }
44
41 struct Lines: View { 45 struct Lines: View {
42 let plot: TablePlot.Plot 46 let plot: TablePlot.Plot
47 let settings: TablePlot.Settings
43 48
44 var body: some View { 49 var body: some View {
45 let series = TablePlot.series(plot) 50 let s = settings
51 // Log axes leave out what they can't place.
52 let series = TablePlot.series(plot).map { series in
53 var series = series
54 series.points.removeAll { point in
55 if s.logY, !TablePlot.logRange.contains(point.y) { return true }
56 if s.logX, case .number(let n) = point.x, !TablePlot.logRange.contains(n) { return true }
57 return false
58 }
59 return series
60 }
46 let o = plot.options 61 let o = plot.options
47 let ys = series.flatMap { $0.points.map(\.y) } 62 let ys = series.flatMap { $0.points.map(\.y) }
48 let xs = series.flatMap { $0.points.compactMap { if case .number(let n) = $0.x { n } else { nil } } } 63 let xs = series.flatMap { $0.points.compactMap { if case .number(let n) = $0.x { n } else { nil } } }
49 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 } }
50 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 } } }
51 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
52 let chart = Chart { 70 let chart = Chart {
53 ForEach(Array(series.enumerated()), id: \.offset) { _, s in 71 ForEach(Array(series.enumerated()), id: \.offset) { _, s in
54 ForEach(Array(s.points.enumerated()), id: \.offset) { _, point in 72 ForEach(Array(s.points.enumerated()), id: \.offset) { _, point in
55 mark(point.x, point.y, series: s.label) 73 mark(point.x, point.y, base: logBars?.low, series: s.label)
56 } 74 }
57 } 75 }
58 } 76 }
59 .chartYAxis { AxisMarks(values: .automatic(desiredCount: ticks ?? 5)) } 77 .chartXAxis {
60 .chartLegend(series.count > 1 ? .visible : .hidden) 78 AxisMarks(values: s.xtics.map { AxisMarkValues.stride(by: $0) } ?? .automatic) { _ in
79 if s.grid { AxisGridLine() }
80 AxisTick()
81 AxisValueLabel()
82 }
83 }
84 .chartYAxis {
85 AxisMarks(values: s.ytics.map { AxisMarkValues.stride(by: $0) } ?? .automatic(desiredCount: ticks ?? 5)) { _ in
86 if s.grid { AxisGridLine() }
87 AxisTick()
88 AxisValueLabel()
89 }
90 }
91 .chartXAxisLabel { if let label = s.xlabel { Text(label) } }
92 .chartYAxisLabel { if let label = s.ylabel { Text(label) } }
93 .key(s.key, shown: series.count > 1)
61 // As gnuplot autoscales: to the data, from zero for bars. 94 // As gnuplot autoscales: to the data, from zero for bars.
95 let yType: ScaleType? = s.logY ? .log : nil, xType: ScaleType? = s.logX ? .log : nil
62 let y = Group { 96 let y = Group {
63 if let domain = PlotChart.domain(o["ymin"], o["ymax"], values: ys) { 97 if let logBars {
64 chart.chartYScale(domain: domain) 98 chart.chartYScale(domain: logBars.low...logBars.high, type: yType)
99 } else if let domain = PlotChart.domain(yGiven.low, yGiven.high, values: ys) {
100 chart.chartYScale(domain: domain, type: yType)
65 } else { 101 } else {
66 chart.chartYScale(domain: .automatic(includesZero: bars)) 102 chart.chartYScale(domain: .automatic(includesZero: bars && !s.logY), type: yType)
67 } 103 }
68 } 104 }
69 if numericX, let domain = PlotChart.domain(o["xmin"], o["xmax"], values: xs) { 105 if numericX, let domain = PlotChart.domain(s.xrange?.low ?? PlotChart.number(o["xmin"]), s.xrange?.high ?? PlotChart.number(o["xmax"]), values: xs) {
70 y.chartXScale(domain: domain) 106 y.chartXScale(domain: domain, type: xType)
71 } else if numericX { 107 } else if numericX {
72 y.chartXScale(domain: .automatic(includesZero: false)) 108 y.chartXScale(domain: .automatic(includesZero: false), type: xType)
73 } else { 109 } else {
74 y 110 y
75 } 111 }
76 } 112 }
77 113
78 @ChartContentBuilder 114 @ChartContentBuilder
79 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 {
80 switch x { 116 switch x {
81 case .number(let n): marks(.value("x", n), y, series) 117 case .number(let n): marks(.value("x", n), y, base, series)
82 case .date(let d): marks(.value("x", d), y, series) 118 case .date(let d): marks(.value("x", d), y, base, series)
83 case .label(let l): marks(.value("x", l), y, series) 119 case .label(let l): marks(.value("x", l), y, base, series)
84 } 120 }
85 } 121 }
86 122
87 @ChartContentBuilder 123 @ChartContentBuilder
88 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 {
89 switch plot.options.with { 125 switch plot.options.with {
90 case "points", "dots": 126 case "points", "dots":
91 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))
92 case "linespoints": 128 case "linespoints":
93 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))
94 case "impulses": 130 case "impulses":
95 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 }
96 case "boxes", "histograms", "hist": 136 case "boxes", "histograms", "hist":
97 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 }
98 case "steps": 142 case "steps":
99 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)
100 case "fsteps": 144 case "fsteps":
@@ -107,6 +151,7 @@ public struct PlotChart: View {
107 151
108 struct HeatMap: View { 152 struct HeatMap: View {
109 let plot: TablePlot.Plot 153 let plot: TablePlot.Plot
154 let settings: TablePlot.Settings
110 155
111 var body: some View { 156 var body: some View {
112 let (values, rowLabels) = TablePlot.matrix(plot) 157 let (values, rowLabels) = TablePlot.matrix(plot)
@@ -124,6 +169,9 @@ public struct PlotChart: View {
124 // The first row at the bottom, as gnuplot draws it. 169 // The first row at the bottom, as gnuplot draws it.
125 .chartYScale(domain: values.indices.reversed().map { rowName($0, rowLabels) }) 170 .chartYScale(domain: values.indices.reversed().map { rowName($0, rowLabels) })
126 .chartXScale(domain: columnLabels) 171 .chartXScale(domain: columnLabels)
172 .chartXAxisLabel { if let label = settings.xlabel { Text(label) } }
173 .chartYAxisLabel { if let label = settings.ylabel { Text(label) } }
174 .key(settings.key, shown: true)
127 } 175 }
128 176
129 func rowName(_ r: Int, _ labels: [String]) -> String { r < labels.count ? labels[r] : "\(r + 1)" } 177 func rowName(_ r: Int, _ labels: [String]) -> String { r < labels.count ? labels[r] : "\(r + 1)" }
@@ -165,6 +213,98 @@ public struct PlotChart: View {
165 } 213 }
166} 214}
167 215
216extension View {
217 /// The legend as `set key` places it, else shown or not.
218 func key(_ key: TablePlot.Settings.Key?, shown: Bool) -> some View {
219 let visible = key.map { $0 != .off } ?? shown
220 return chartLegend(visible ? .visible : .hidden).chartLegend(position: PlotChart.keyPosition(key))
221 }
222}
223
224extension PlotChart {
225 /// Where `set key` puts the legend; gnuplot keeps a direction not given at its default, right top.
226 static func keyPosition(_ key: TablePlot.Settings.Key?) -> AnnotationPosition {
227 guard case .at(let vertical, let horizontal) = key else { return .automatic }
228 switch (vertical ?? "top", horizontal ?? "right") {
229 case ("top", "left"): return .topLeading
230 case ("top", "right"): return .topTrailing
231 case ("bottom", "left"): return .bottomLeading
232 case ("bottom", "right"): return .bottomTrailing
233 default: return .automatic
234 }
235 }
236}
237
238/// A radar plot as org-plot's gnuplot script draws it: an axis per row, clockwise from the
239/// top, each scaled from its low to its high value; a web at each tick; each series filled.
240struct Radar: View {
241 let radar: TablePlot.Radar
242
243 var body: some View {
244 VStack(spacing: 8) {
245 Canvas { context, size in
246 let n = radar.axes.count
247 guard n > 0 else { return }
248 let center = CGPoint(x: size.width / 2, y: size.height / 2)
249 // gnuplot's range is 1.4 times the axes' length each way.
250 let unit = min(size.width, size.height) / 2 / 1.4
251 func point(_ axis: Int, _ r: Double, offset: Double = 0) -> CGPoint {
252 let angle = (90 - Double(axis) * 360 / Double(n)) * .pi / 180
253 return CGPoint(x: center.x + (r * cos(angle) + offset * sin(angle)) * unit,
254 y: center.y - (r * sin(angle) - offset * cos(angle)) * unit)
255 }
256 let count = radar.ticks == 0 ? 2 : radar.ticks
257 if radar.ticks != 0 {
258 for i in 1...count {
259 let r = Double(i) / Double(count)
260 var web = Path()
261 web.move(to: point(0, r))
262 for axis in 1...n { web.addLine(to: point(axis % n, r)) }
263 context.stroke(web, with: .color(.secondary), style: StrokeStyle(lineWidth: 0.5, dash: [3, 3]))
264 for axis in 0..<n {
265 let scale = radar.axes[radar.sharedTicks ? 0 : axis]
266 let value = Double(i) * (scale.high - scale.low) / Double(count) + scale.low
267 context.draw(Text(String(format: "%g", value)).font(.system(size: 8)).foregroundStyle(.secondary), at: point(axis, r, offset: 0.1))
268 }
269 }
270 }
271 for axis in 0..<n {
272 var line = Path()
273 line.move(to: center)
274 line.addLine(to: point(axis, 1.1))
275 context.stroke(line, with: .color(.primary), lineWidth: 1)
276 context.draw(Text(radar.axes[axis].label), at: point(axis, 1.2))
277 }
278 for s in radar.series.indices {
279 var shape = Path()
280 for (axis, a) in radar.axes.enumerated() where s < a.values.count && a.high != a.low {
281 let p = point(axis, (a.values[s] - a.low) / (a.high - a.low))
282 if shape.isEmpty { shape.move(to: p) } else { shape.addLine(to: p) }
283 }
284 shape.closeSubpath()
285 context.fill(shape, with: .color(Radar.color(s).opacity(0.2)))
286 context.stroke(shape, with: .color(Radar.color(s)), lineWidth: 1.5)
287 }
288 }
289 .aspectRatio(1, contentMode: .fit)
290 HStack(spacing: 16) {
291 ForEach(Array(radar.series.enumerated()), id: \.offset) { s, name in
292 HStack(spacing: 4) {
293 Rectangle().fill(Radar.color(s).opacity(0.4)).frame(width: 16, height: 10)
294 Text(name).font(.caption)
295 }
296 }
297 }
298 }
299 }
300
301 /// gnuplot's colour for series `i`.
302 static func color(_ i: Int) -> Color {
303 let v = Int(TablePlot.colors[i % TablePlot.colors.count].dropFirst(), radix: 16) ?? 0
304 return Color(red: Double(v >> 16 & 255) / 255, green: Double(v >> 8 & 255) / 255, blue: Double(v & 255) / 255)
305 }
306}
307
168/// A matrix as gnuplot's `splot … matrix with lines` draws it: a wireframe seen from its 308/// A matrix as gnuplot's `splot … matrix with lines` draws it: a wireframe seen from its
169/// default view, rows and columns along the floor and values up. 309/// default view, rows and columns along the floor and values up.
170struct Wireframe: View { 310struct Wireframe: View {
@@ -227,8 +367,39 @@ public enum PlotOutput {
227 return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: OrgPaths.home)).appendingPathComponent(expanded) 367 return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: OrgPaths.home)).appendingPathComponent(expanded)
228 } 368 }
229 369
230 /// The chart as gnuplot's default 640×480, as PNG, JPEG or PDF by the file's extension. 370 /// The options a chart drawn here leaves out, for the result message.
371 public static func note(_ plot: TablePlot.Plot) -> String? {
372 let unfollowed = TablePlot.settings(plot).unfollowed
373 return unfollowed.isEmpty ? nil : "Not followed without gnuplot: " + unfollowed.joined(separator: ", ")
374 }
375
376 /// Refuses what the chart can't draw: a radar plot `TablePlot.radar` refuses, which
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.
379 public static func check(_ plot: TablePlot.Plot) throws {
380 switch plot.options.type {
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 }
392 }
393
394 /// The chart as gnuplot's default 640×480, as PNG, JPEG, PDF or SVG by the file's extension.
231 public static func write(_ plot: TablePlot.Plot, to url: URL) throws { 395 public static func write(_ plot: TablePlot.Plot, to url: URL) throws {
396 try check(plot)
397 if url.pathExtension.lowercased() == "svg" {
398 let svg: String
399 do { svg = try TablePlot.svg(plot) } catch { throw Failure(description: "\(error)") }
400 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
401 return try svg.write(to: url, atomically: true, encoding: .utf8)
402 }
232 let renderer = ImageRenderer(content: PlotChart(plot, still: true).frame(width: 640, height: 480).background(Color.white).environment(\.colorScheme, .light)) 403 let renderer = ImageRenderer(content: PlotChart(plot, still: true).frame(width: 640, height: 480).background(Color.white).environment(\.colorScheme, .light))
233 renderer.scale = 2 404 renderer.scale = 2
234 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) 405 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
@@ -253,7 +424,7 @@ public enum PlotOutput {
253 CGImageDestinationAddImage(destination, image, nil) 424 CGImageDestinationAddImage(destination, image, nil)
254 guard CGImageDestinationFinalize(destination) else { throw Failure(description: "Can't write \(url.lastPathComponent)") } 425 guard CGImageDestinationFinalize(destination) else { throw Failure(description: "Can't write \(url.lastPathComponent)") }
255 default: 426 default:
256 throw Failure(description: "Without gnuplot, plots are written as .png, .jpg or .pdf, not .\(url.pathExtension)") 427 throw Failure(description: "Without gnuplot, plots are written as .png, .jpg, .pdf or .svg, not .\(url.pathExtension)")
257 } 428 }
258 } 429 }
259} 430}
Sources/OrgCore/Compute/PlotSVG.swift added +189
@@ -0,0 +1,189 @@
1import Foundation
2
3/// A 2d plot as an SVG file, 640×480 as gnuplot's default: lines, points or bars by `with:`,
4/// with the `set` commands `settings` follows.
5extension TablePlot {
6 /// gnuplot's default line colours.
7 public static let colors = ["#9400d3", "#009e73", "#56b4e9", "#e69f00", "#f0e442", "#0072b2", "#e51e10", "#000000"]
8
9 /// 1, 2 or 5 times a power of ten, near a fifth of `span`.
10 static func niceStep(_ span: Double) -> Double {
11 let raw = span / 5, power = pow(10, (log10(raw)).rounded(.down)), f = raw / power
12 return power * (f < 1.5 ? 1 : f < 3.5 ? 2 : f < 7.5 ? 5 : 10)
13 }
14
15 /// What a log axis places; gnuplot skips undefined points, and Swift Charts traps past these.
16 public static let logRange = 1e-307...1e308
17
18 /// An axis: its ends, widened to whole steps where they're not given, and its ticks.
19 public struct Axis {
20 public var low: Double
21 public var high: Double
22 var log: Bool
23 var ticks: [Double] = []
24
25 public init(values: [Double], given: Settings.Range?, log: Bool, step: Double?, zero: Bool) throws {
26 var data = values.filter { !log || TablePlot.logRange.contains($0) }
27 // gnuplot refuses these too.
28 if log, data.isEmpty, given?.low == nil || given?.high == nil { throw Failure(description: "A log axis needs values above 0") }
29 if log, [given?.low, given?.high].contains(where: { ($0 ?? 1) <= 0 }) { throw Failure(description: "A log axis's range must be above 0") }
30 if log, [given?.low, given?.high].contains(where: { !TablePlot.logRange.contains($0 ?? 1) }) { throw Failure(description: "A log axis's range must be within 1e-307 to 1e308") }
31 if zero, !log { data.append(0) }
32 var low = given?.low ?? data.min() ?? 0, high = given?.high ?? data.max() ?? 1
33 if low == high { (low, high) = log ? (low / 10, high * 10) : (low - 1, high + 1) }
34 if low > high { swap(&low, &high) }
35 self.log = log
36 if log {
37 if given?.low == nil { low = pow(10, log10(low).rounded(.down)) }
38 if given?.high == nil { high = pow(10, log10(high).rounded(.up)) }
39 guard TablePlot.logRange.contains(low), TablePlot.logRange.contains(high) else { throw Failure(description: "A log axis's range must be within 1e-307 to 1e308") }
40 let first = log10(low).rounded(.up), last = log10(high).rounded(.down)
41 // A range with no power of ten in it is labelled at its ends.
42 ticks = first <= last ? Array(Int(first)...Int(last)).map { pow(10, Double($0)) } : [low, high]
43 } else {
44 let step = step ?? TablePlot.niceStep(high - low)
45 if given?.low == nil { low = (low / step).rounded(.down) * step }
46 if given?.high == nil { high = (high / step).rounded(.up) * step }
47 var t = (low / step).rounded(.up) * step
48 while t <= high + step * 1e-9, ticks.count < 200 { ticks.append(abs(t) < step * 1e-9 ? 0 : t); t += step }
49 }
50 self.low = low
51 self.high = high
52 }
53
54 func fraction(_ v: Double) -> Double {
55 log ? (log10(v) - log10(low)) / (log10(high) - log10(low)) : (v - low) / (high - low)
56 }
57 }
58
59 static func escaped(_ s: String) -> String {
60 s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
61 .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
62 }
63
64 static func number(_ v: Double) -> String { String(format: "%.2f", v) }
65
66 public static func svg(_ plot: Plot, calendar: Calendar = .current) throws -> String {
67 guard plot.options.type == "2d" else {
68 throw Failure(description: "Without gnuplot, only 2d plots are written as .svg; use .png, .jpg or .pdf")
69 }
70 let s = settings(plot), with = plot.options.with
71 let series = series(plot, calendar: calendar)
72 let bars = ["boxes", "histograms", "hist"].contains(with)
73 var categories: [String] = []
74 for p in series.flatMap(\.points) { if case .label(let l) = p.x, !categories.contains(l) { categories.append(l) } }
75 let dates = series.contains { $0.points.contains { if case .date = $0.x { true } else { false } } }
76 func xValue(_ x: Series.X) -> Double {
77 switch x {
78 case .number(let n): n
79 case .date(let d): d.timeIntervalSince1970
80 case .label(let l): Double(categories.firstIndex(of: l)!)
81 }
82 }
83 func bound(_ key: String) -> Double? { if case .number(let n)? = plot.options[key] { n } else { nil } }
84 func given(_ set: Settings.Range?, _ low: String, _ high: String) -> Settings.Range? {
85 let r = Settings.Range(low: set?.low ?? bound(low), high: set?.high ?? bound(high))
86 return r.low == nil && r.high == nil ? nil : r
87 }
88 let ys = series.flatMap { $0.points.map(\.y) }
89 let y = try Axis(values: ys, given: given(s.yrange, "ymin", "ymax"), log: s.logY, step: s.ytics, zero: bars || with == "impulses")
90 var x: Axis
91 if !categories.isEmpty {
92 x = try Axis(values: [], given: .init(low: -0.5, high: Double(categories.count) - 0.5), log: false, step: 1, zero: false)
93 x.ticks = categories.indices.map(Double.init)
94 } else {
95 x = try Axis(values: series.flatMap { $0.points.map { xValue($0.x) } }, given: given(s.xrange, "xmin", "xmax"), log: s.logX, step: s.xtics, zero: false)
96 }
97
98 let width = 640.0, height = 480.0
99 let left = 60.0 + (s.ylabel == nil ? 0 : 20), right = 620.0
100 let top = 20.0 + (s.title == nil ? 0 : 20), bottom = height - 40 - (s.xlabel == nil ? 0 : 20)
101 func px(_ v: Double) -> Double { left + x.fraction(v) * (right - left) }
102 func py(_ v: Double) -> Double { bottom - y.fraction(v) * (bottom - top) }
103 func xLabel(_ t: Double) -> String {
104 if !categories.isEmpty { return categories[Int(t)] }
105 if dates {
106 let c = calendar.dateComponents([.year, .month, .day], from: Date(timeIntervalSince1970: t))
107 return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)
108 }
109 return String(format: "%g", t)
110 }
111
112 var out = """
113 <svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480" font-family="Helvetica, Arial, sans-serif" font-size="12">
114 <rect width="\(Int(width))" height="\(Int(height))" fill="white"/>
115 <clipPath id="plot"><rect x="\(number(left))" y="\(number(top))" width="\(number(right - left))" height="\(number(bottom - top))"/></clipPath>
116
117 """
118 func add(_ line: String) { out += line + "\n" }
119 for t in x.ticks where t >= x.low && t <= x.high {
120 if s.grid { add("<line x1=\"\(number(px(t)))\" y1=\"\(number(top))\" x2=\"\(number(px(t)))\" y2=\"\(number(bottom))\" stroke=\"#a0a0a0\" stroke-dasharray=\"2,3\"/>") }
121 add("<line x1=\"\(number(px(t)))\" y1=\"\(number(bottom))\" x2=\"\(number(px(t)))\" y2=\"\(number(bottom - 6))\" stroke=\"black\"/>")
122 add("<text x=\"\(number(px(t)))\" y=\"\(number(bottom + 16))\" text-anchor=\"middle\">\(escaped(xLabel(t)))</text>")
123 }
124 for t in y.ticks where t >= y.low && t <= y.high {
125 if s.grid { add("<line x1=\"\(number(left))\" y1=\"\(number(py(t)))\" x2=\"\(number(right))\" y2=\"\(number(py(t)))\" stroke=\"#a0a0a0\" stroke-dasharray=\"2,3\"/>") }
126 add("<line x1=\"\(number(left))\" y1=\"\(number(py(t)))\" x2=\"\(number(left + 6))\" y2=\"\(number(py(t)))\" stroke=\"black\"/>")
127 add("<text x=\"\(number(left - 6))\" y=\"\(number(py(t) + 4))\" text-anchor=\"end\">\(escaped(String(format: "%g", t)))</text>")
128 }
129 add("<rect x=\"\(number(left))\" y=\"\(number(top))\" width=\"\(number(right - left))\" height=\"\(number(bottom - top))\" fill=\"none\" stroke=\"black\"/>")
130 if let title = s.title { add("<text x=\"320\" y=\"24\" text-anchor=\"middle\" font-size=\"14\">\(escaped(title))</text>") }
131 if let label = s.xlabel { add("<text x=\"\(number((left + right) / 2))\" y=\"\(number(height - 12))\" text-anchor=\"middle\">\(escaped(label))</text>") }
132 if let label = s.ylabel { add("<text transform=\"translate(16 \(number((top + bottom) / 2))) rotate(-90)\" text-anchor=\"middle\">\(escaped(label))</text>") }
133
134 add("<g clip-path=\"url(#plot)\">")
135 let xs = series.flatMap { $0.points.map { xValue($0.x) } }.sorted()
136 let spacing = categories.isEmpty ? zip(xs, xs.dropFirst()).map { $1 - $0 }.filter { $0 > 0 }.min().map { abs(px(xs[0] + $0) - px(xs[0])) } ?? 40 : (px(1) - px(0))
137 let base = py(y.log ? y.low : min(max(0, y.low), y.high))
138 for (i, s) in series.enumerated() {
139 let color = colors[i % colors.count]
140 let points = s.points.filter { (!y.log || logRange.contains($0.y)) && (!x.log || logRange.contains(xValue($0.x))) }.map { (px(xValue($0.x)), py($0.y)) }
141 guard !points.isEmpty else { continue }
142 func polyline(_ p: [(Double, Double)]) {
143 add("<polyline fill=\"none\" stroke=\"\(color)\" stroke-width=\"1.5\" points=\"" + p.map { "\(number($0.0)),\(number($0.1))" }.joined(separator: " ") + "\"/>")
144 }
145 switch with {
146 case "points", "dots", "linespoints":
147 if with == "linespoints" { polyline(points) }
148 for (px, py) in points { add("<circle cx=\"\(number(px))\" cy=\"\(number(py))\" r=\"\(with == "dots" ? 1 : 3)\" fill=\"none\" stroke=\"\(color)\"/>") }
149 case "impulses":
150 for (px, py) in points { add("<line x1=\"\(number(px))\" y1=\"\(number(base))\" x2=\"\(number(px))\" y2=\"\(number(py))\" stroke=\"\(color)\" stroke-width=\"1.5\"/>") }
151 case "boxes", "histograms", "hist":
152 let group = spacing * 0.8, bar = group / Double(series.count)
153 for (px, py) in points {
154 let x0 = px - group / 2 + bar * Double(i)
155 add("<rect x=\"\(number(x0))\" y=\"\(number(min(py, base)))\" width=\"\(number(bar))\" height=\"\(number(abs(base - py)))\" fill=\"\(color)\" fill-opacity=\"0.8\" stroke=\"\(color)\"/>")
156 }
157 case "steps", "fsteps":
158 var stepped = [points[0]]
159 for p in points.dropFirst() {
160 stepped.append(with == "steps" ? (p.0, stepped.last!.1) : (stepped.last!.0, p.1))
161 stepped.append(p)
162 }
163 polyline(stepped)
164 default:
165 polyline(points)
166 }
167 }
168 add("</g>")
169
170 var showKey = true, vertical = "top", horizontal = "right"
171 switch s.key {
172 case .off: showKey = false
173 case .at(let v, let h): vertical = v ?? vertical; horizontal = h ?? horizontal
174 case nil: break
175 }
176 if showKey {
177 for (i, s) in series.enumerated() {
178 let color = colors[i % colors.count]
179 let row = vertical == "top" ? top + 16 + Double(i) * 16 : bottom - 10 - Double(series.count - 1 - i) * 16
180 let sample = horizontal == "right" ? right - 50 : left + 10
181 let text = horizontal == "right" ? "<text x=\"\(number(sample - 6))\" y=\"\(number(row + 4))\" text-anchor=\"end\">"
182 : "<text x=\"\(number(sample + 46))\" y=\"\(number(row + 4))\">"
183 add(text + escaped(s.label) + "</text>")
184 add("<line x1=\"\(number(sample))\" y1=\"\(number(row))\" x2=\"\(number(sample + 40))\" y2=\"\(number(row))\" stroke=\"\(color)\" stroke-width=\"\(bars ? 8 : 1.5)\"/>")
185 }
186 }
187 return out + "</svg>\n"
188 }
189}
Sources/OrgCore/Compute/PlotSettings.swift added +131
@@ -0,0 +1,131 @@
1import Foundation
2
3/// The gnuplot `set` commands a plot drawn without gnuplot follows, and the options it leaves out.
4extension TablePlot {
5 public struct Settings: Sendable, Equatable {
6 public enum Key: Sendable, Equatable {
7 case off
8 /// `top`/`bottom` and `left`/`right`, either left to the chart.
9 case at(vertical: String?, horizontal: String?)
10 }
11
12 public struct Range: Sendable, Equatable {
13 public var low: Double?
14 public var high: Double?
15
16 public init(low: Double?, high: Double?) {
17 self.low = low
18 self.high = high
19 }
20 }
21
22 public var title: String?
23 public var xlabel: String?
24 public var ylabel: String?
25 public var xrange: Range?
26 public var yrange: Range?
27 public var logX = false
28 public var logY = false
29 public var grid = false
30 public var key: Key?
31 public var xtics: Double?
32 public var ytics: Double?
33 /// The options not followed, as written in `#+PLOT`: `set:"…"`, `line:"…"`, `script:"…"`.
34 public var unfollowed: [String] = []
35 }
36
37 /// The `set` commands each kind of chart can follow.
38 static func followed(_ plot: Plot) -> Set<String> {
39 switch plot.options.type {
40 case "2d":
41 let numericX = plot.options.ind <= 0 || !(plot.timeInd || plot.textInd || plot.options.with == "histograms")
42 return numericX ? ["title", "xlabel", "ylabel", "xrange", "yrange", "logscale", "grid", "key", "xtics", "ytics"]
43 : ["title", "xlabel", "ylabel", "yrange", "logscale y", "grid", "key", "ytics"]
44 // The heat map's legend is its colour scale, which gnuplot's `set key` leaves alone.
45 case "grid": return ["title", "xlabel", "ylabel"]
46 case "3d" where plot.options["map"]?.truthy == true: return ["title", "xlabel", "ylabel"]
47 // The radar script sets its own key, after these.
48 default: return ["title"]
49 }
50 }
51
52 /// The script's `title:`, `line:` and `set:` in the order gnuplot reads them, so a later
53 /// one wins.
54 public static func settings(_ plot: Plot) -> Settings {
55 var s = Settings()
56 let o = plot.options
57 var follows = followed(plot)
58 func read() -> (lines: [String], sets: [String]) {
59 s = Settings()
60 s.title = o.title
61 var lines: [String] = [], sets: [String] = []
62 for line in o.lines {
63 if !(line.hasPrefix("set ") && apply(String(line.dropFirst(4)), to: &s, follows: follows)) { lines.append("line:\"\(line)\"") }
64 }
65 for set in o.sets where !apply(set, to: &s, follows: follows) { sets.append("set:\"\(set)\"") }
66 return (lines, sets)
67 }
68 var (lines, sets) = read()
69 // On a log axis gnuplot steps by a factor, not an increment.
70 if s.logX || s.logY {
71 if s.logX { follows.remove("xtics") }
72 if s.logY { follows.remove("ytics") }
73 (lines, sets) = read()
74 }
75 // Each comes twice, as Org reads the options twice; list them once, as written.
76 for u in lines.reversed() + sets.reversed() where !s.unfollowed.contains(u) { s.unfollowed.append(u) }
77 if let script = o["script"] { s.unfollowed.append("script:\"\(script)\"") }
78 return s
79 }
80
81 static func apply(_ command: String, to s: inout Settings, follows: Set<String>) -> Bool {
82 let words = command.split(separator: " ", maxSplits: 1).map(String.init)
83 guard let name = words.first else { return false }
84 let rest = words.count > 1 ? words[1].trimmingCharacters(in: .whitespaces) : ""
85 func quoted() -> String? {
86 guard let m = rest.firstMatch(of: /^(["'])(.*)\1$/) else { return nil }
87 return String(m.2)
88 }
89 func range() -> Settings.Range? {
90 guard let m = rest.firstMatch(of: /^\[\s*([^:\]]*?)\s*:\s*([^:\]]*?)\s*\]$/) else { return nil }
91 func bound(_ t: Substring) -> Double?? { t.isEmpty || t == "*" ? .some(nil) : Double(t).map { .some($0) } }
92 guard let low = bound(m.1), let high = bound(m.2) else { return nil }
93 // gnuplot reverses the axis for these, which the charts here don't.
94 if let low, let high, low > high { return nil }
95 return Settings.Range(low: low, high: high)
96 }
97 func step() -> Double? { Double(rest).flatMap { $0 > 0 ? $0 : nil } }
98 switch name {
99 case "title", "xlabel", "ylabel":
100 guard follows.contains(name), let text = quoted() else { return false }
101 if name == "title" { s.title = text } else if name == "xlabel" { s.xlabel = text } else { s.ylabel = text }
102 case "xrange", "yrange":
103 guard follows.contains(name), let r = range() else { return false }
104 if name == "xrange" { s.xrange = r } else { s.yrange = r }
105 case "logscale":
106 let axes = rest.isEmpty ? "xy" : rest
107 guard ["x", "y", "xy", "yx"].contains(axes), follows.contains("logscale") || (axes == "y" && follows.contains("logscale y")) else { return false }
108 if axes.contains("x") { s.logX = true }
109 if axes.contains("y") { s.logY = true }
110 case "grid":
111 guard follows.contains(name), rest.isEmpty else { return false }
112 s.grid = true
113 case "key":
114 let words = rest.split(separator: " ").map(String.init)
115 guard follows.contains(name), words.allSatisfy(["off", "top", "bottom", "left", "right"].contains) else { return false }
116 if words == ["off"] {
117 s.key = .off
118 } else {
119 let vertical = words.filter { $0 == "top" || $0 == "bottom" }, horizontal = words.filter { $0 == "left" || $0 == "right" }
120 guard !words.contains("off"), vertical.count <= 1, horizontal.count <= 1 else { return false }
121 s.key = .at(vertical: vertical.first, horizontal: horizontal.first)
122 }
123 case "xtics", "ytics":
124 guard follows.contains(name), let step = step() else { return false }
125 if name == "xtics" { s.xtics = step } else { s.ytics = step }
126 default:
127 return false
128 }
129 return true
130 }
131}
Sources/OrgCore/Compute/TablePlot.swift +8 −6
@@ -132,8 +132,8 @@ public enum TablePlot {
132 } 132 }
133 let first = table.first.flatMap { $0 } ?? (table.count > 1 ? table[1] : nil) 133 let first = table.first.flatMap { $0 } ?? (table.count > 1 ? table[1] : nil)
134 let columns = first?.count ?? 0 134 let columns = first?.count ?? 0
135 guard ["2d", "3d", "grid"].contains(options.type) else { 135 guard ["2d", "3d", "grid", "radar"].contains(options.type) else {
136 throw Failure(description: options.type == "radar" ? "Radar plots need gnuplot" : "Org-plot type `\(options.type)' is undefined") 136 throw Failure(description: "Org-plot type `\(options.type)' is undefined")
137 } 137 }
138 if table.count > 1, table[1] == nil, let header = table[0] { 138 if table.count > 1, table[1] == nil, let header = table[0] {
139 options.values["labels"] = .list(header.map { .string($0) }) 139 options.values["labels"] = .list(header.map { .string($0) })
@@ -152,6 +152,7 @@ public enum TablePlot {
152 } 152 }
153 } 153 }
154 } 154 }
155 if options.type == "radar", options["script"] == nil { _ = try radar(plot) }
155 return plot 156 return plot
156 } 157 }
157 158
@@ -235,15 +236,14 @@ public enum TablePlot {
235 236
236 /// `string-to-number`: the leading number, else 0. 237 /// `string-to-number`: the leading number, else 0.
237 static func stringToNumber(_ s: String) -> Double { 238 static func stringToNumber(_ s: String) -> Double {
238 let trimmed = s.drop { $0 == " " || $0 == "\t" } 239 lispNumber(s).value
239 guard let m = trimmed.firstMatch(of: /^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?/) else { return 0 }
240 return Double(m.0) ?? 0
241 } 240 }
242 241
243 /// `org-plot/gnuplot-script`, with `org-plot/gnuplot-term-extra` and the preamble empty. 242 /// `org-plot/gnuplot-script`, with `org-plot/gnuplot-term-extra` and the preamble empty.
244 /// `output` is where `file:` goes, expanded. A `preface` leaves out the plot command, for 243 /// `output` is where `file:` goes, expanded. A `preface` leaves out the plot command, for
245 /// a `script:` file to follow. 244 /// a `script:` file to follow.
246 public static func script(_ plot: Plot, dataFile: String, output: String?, yLabels: [(Int, String)] = [], preface: Bool = false) -> String { 245 /// `setupFile` is where a radar plot's `radarSetup` goes.
246 public static func script(_ plot: Plot, dataFile: String, output: String?, yLabels: [(Int, String)] = [], preface: Bool = false, setupFile: String = "") -> String {
247 let o = plot.options 247 let o = plot.options
248 var script = "reset" 248 var script = "reset"
249 func add(_ line: String?) { if let line { script += "\n" + line } } 249 func add(_ line: String?) { if let line { script += "\n" + line } }
@@ -281,6 +281,8 @@ public enum TablePlot {
281 add("plot " + plotLines.joined(separator: ",\\\n ")) 281 add("plot " + plotLines.joined(separator: ",\\\n "))
282 case "3d": 282 case "3d":
283 add("splot '\(dataFile)' matrix with \(with) title ''") 283 add("splot '\(dataFile)' matrix with \(with) title ''")
284 case "radar":
285 if let radar = try? radar(plot) { add(radarScript(radar, setupFile: setupFile)) }
284 default: 286 default:
285 add("splot '\(dataFile)' with \(with) title ''") 287 add("splot '\(dataFile)' with \(with) title ''")
286 } 288 }
Sources/OrgCore/Compute/TablePlotRadar.swift added +250
@@ -0,0 +1,250 @@
1import Foundation
2
3/// `type:radar` (`org--plot/radar`, Org 9.8.7): each row is an axis with its own scale, each
4/// column after the first a series.
5extension TablePlot {
6 public struct Radar: Sendable, Equatable {
7 public struct Axis: Sendable, Equatable {
8 public var label: String
9 public var fields: [String]
10 public var values: [Double]
11 public var low: Double
12 public var high: Double
13 /// `low` and `high` as `format "%s"` prints them.
14 var lowText: String
15 var highText: String
16 }
17 public var axes: [Axis]
18 /// The header's names after the first, one per series.
19 public var series: [String]
20 /// The web's rings; 0 draws none.
21 public var ticks: Int
22 /// With both `ymin` and `ymax`, every axis is labelled with the first axis's values.
23 public var sharedTicks: Bool
24 }
25
26 /// A number as `string-to-number` reads it, and whether it's an integer.
27 static func lispNumber(_ s: String) -> (value: Double, integer: Bool) {
28 let trimmed = s.drop { $0 == " " || $0 == "\t" }
29 guard let m = trimmed.firstMatch(of: /^([-+]?)([0-9]+\.?[0-9]*|\.[0-9]+)([eE]([-+]?[0-9]+|\+INF|\+NaN))?/) else { return (0, true) }
30 let text = String(m.0), sign: Double = m.1 == "-" ? -1 : 1
31 // The reader's `1.0e+INF` and `1.0e+NaN`.
32 if text.hasSuffix("INF") { return (sign * .infinity, false) }
33 if text.hasSuffix("NaN") { return (sign * .nan, false) }
34 return (Double(text) ?? 0, text.firstMatch(of: /\.[0-9]|[eE]/) == nil)
35 }
36
37 static func printed(_ n: (value: Double, integer: Bool)) -> String {
38 n.integer && abs(n.value) < 0x1p63 ? String(Int(n.value)) : Elisp.floatText(n.value)
39 }
40
41 /// An integer field as Emacs prints what `string-to-number` reads from it, bignums included.
42 static func integerText(_ field: String) -> String {
43 let trimmed = field.drop { $0 == " " || $0 == "\t" }
44 guard let m = trimmed.firstMatch(of: /^([-+]?)0*([0-9]+)/) else { return "0" }
45 let digits = String(m.2)
46 return (m.1 == "-" && digits != "0" ? "-" : "") + digits
47 }
48
49 /// `org--plot/values-stats`.
50 static func stats(_ nums: [(value: Double, integer: Bool)], hardMin: Double? = nil, hardMax: Double? = nil)
51 -> (factor: Double, niceMin: (value: Double, integer: Bool), niceMax: (value: Double, integer: Bool)) {
52 // Emacs's `min` and `max` return a NaN argument.
53 let values = nums.map(\.value), nan = values.contains { $0.isNaN }
54 let low = hardMin ?? (nan ? .nan : values.min()!), high = hardMax ?? (nan ? .nan : values.max()!)
55 let range = high - low
56 guard range != 0 else { return (1, nums[0], nums[0]) }
57 let order = (1 - log10(range)).rounded(.up)
58 let factor = pow(10, order)
59 return (factor, ((low * factor).rounded(.down) / factor, false), ((high * factor).rounded(.up) / factor, false))
60 }
61
62 /// `org--plot/sensible-tick-num`, or nil where Emacs signals an error or never returns.
63 static func sensibleTicks(_ rows: [[String]], hardMin: Double?, hardMax: Double?) -> Int? {
64 var decompositions: [[(Int, Double)]] = []
65 for row in rows {
66 let s = stats(row.dropFirst().map(lispNumber), hardMin: hardMin, hardMax: hardMax)
67 let raw = (s.factor * (s.niceMax.value - s.niceMin.value)).rounded(.toNearestOrEven)
68 // A ymin above a row's values or a ymax below them: `ceiling` of NaN signals overflow-error.
69 guard raw.isFinite, raw >= 0, raw < 0x1p63 else { return nil }
70 var value = Int(raw)
71 if value % 10 == 0 { value /= 10 }
72 // `org--plot/prime-factors` loops forever on 0.
73 guard value > 0 else { return nil }
74 var factors: [Int] = [], i = 1
75 while value != 1 {
76 i += 1
77 if value % i == 0 { factors.insert(i, at: 0); value /= i; i -= 1 }
78 }
79 // `org--plot/item-frequencies`, keys in `seq-group-by`'s order.
80 var groups: [(Int, Int)] = []
81 for f in factors.reversed() {
82 if let at = groups.firstIndex(where: { $0.0 == f }) { groups[at].1 += 1 } else { groups.insert((f, 1), at: 0) }
83 }
84 decompositions.append(groups.map { ($0.0, Double($0.1) / Double(factors.count)) })
85 }
86 // `org--plot/merge-alists` needs two lists.
87 func merge(_ lists: ArraySlice<[(Int, Double)]>) -> [(Int, Double)] {
88 let a1 = lists.first!
89 let a2 = lists.count > 2 ? merge(lists.dropFirst()) : lists[lists.startIndex + 1]
90 // `cl-union` with :test: the longer list, the shorter's new keys pushed on its front.
91 var (keys, other) = (a1.map(\.0), a2.map(\.0))
92 if !keys.isEmpty, !other.isEmpty {
93 if keys.count < other.count { swap(&keys, &other) }
94 for k in other where !keys.contains(k) { keys.insert(k, at: 0) }
95 } else if keys.isEmpty {
96 keys = other
97 }
98 func lookup(_ k: Int, _ list: [(Int, Double)]) -> Double { list.first { $0.0 == k }?.1 ?? 0 }
99 return keys.map { ($0, lookup($0, a1) + lookup($0, a2)) }
100 }
101 guard decompositions.count >= 2 else { return nil }
102 let weighted = merge(decompositions[...]).enumerated().sorted { $0.element.1 != $1.element.1 ? $0.element.1 > $1.element.1 : $0.offset < $1.offset }.map(\.element)
103 // `org--plot/nice-frequency-pick`.
104 var pick: [Int]
105 switch weighted.count {
106 case 0: return nil
107 case 1: pick = [weighted[0].0]
108 case 2: pick = 3 <= weighted[0].1 / weighted[1].1 ? [weighted[0].0, weighted[0].0] : [weighted[0].0, weighted[1].0]
109 default:
110 let total = weighted.map(\.1).reduce(0, +)
111 let n = weighted.map { ($0.0, $0.1 / total) }
112 pick = [n[0].0]
113 let r12 = n[0].1 / n[1].1, r23 = n[1].1 / n[2].1, r13 = r12 * r23
114 if r12 > 4 { pick.insert(n[0].0, at: 0) }
115 if r12 < Double(n[1].0), pick.reduce(1, *) * n[1].0 < 30 { pick.insert(n[1].0, at: 0) }
116 if r13 < Double(n[2].0), pick.reduce(1, *) * n[2].0 < 30 { pick.insert(n[2].0, at: 0) }
117 }
118 return pick.reduce(1, *)
119 }
120
121 /// The radar plot's axes, series and ticks, as `org--plot/radar` works them out.
122 public static func radar(_ plot: Plot) throws -> Radar {
123 let rows = plot.rows.compactMap { $0 }
124 guard !rows.isEmpty, rows.allSatisfy({ $0.count > 1 }) else {
125 throw Failure(description: "A radar plot needs a name and a value in each row")
126 }
127 func number(_ key: String) throws -> Double? {
128 guard let v = plot.options[key] else { return nil }
129 guard case .number(let n) = v else { throw Failure(description: "\(key): must be a number") }
130 return n
131 }
132 let ymin = try number("ymin"), ymax = try number("ymax")
133 let ticks: Int
134 if let given = try number("ticks") {
135 // gnuplot can't draw fewer than none.
136 guard given >= 0, given < 0x1p63 else { throw Failure(description: "ticks: is out of range") }
137 ticks = Int(given)
138 } else if let sensible = sensibleTicks(rows, hardMin: ymin, hardMax: ymax) {
139 ticks = sensible
140 } else {
141 throw Failure(description: "Org can't choose this radar plot's ticks; give ticks:")
142 }
143 let axes = try rows.map { row -> Radar.Axis in
144 let nums = row.dropFirst().map(lispNumber)
145 let s = stats(nums)
146 // Emacs scales every row, given ticks: or not; past a double, `ceiling` signals overflow-error.
147 guard s.factor.isFinite, s.niceMin.value.isFinite, s.niceMax.value.isFinite else {
148 throw Failure(description: "Org can't scale the radar row \"\(row[0])\"")
149 }
150 return Radar.Axis(label: row[0], fields: Array(row.dropFirst()), values: nums.map(\.value),
151 low: ymin ?? s.niceMin.value, high: ymax ?? s.niceMax.value,
152 lowText: plot.options["ymin"]?.description ?? (s.niceMin.integer ? integerText(row[1]) : printed(s.niceMin)),
153 highText: plot.options["ymax"]?.description ?? (s.niceMax.integer ? integerText(row[1]) : printed(s.niceMax)))
154 }
155 return Radar(axes: axes, series: Array((plot.options.labels ?? []).dropFirst()), ticks: ticks, sharedTicks: ymin != nil && ymax != nil)
156 }
157
158 /// The setup file `org--plot/radar` writes: the data and each axis's scale.
159 public static func radarSetup(_ plot: Plot) throws -> String {
160 let radar = try radar(plot)
161 let axes = radar.axes + radar.axes.prefix(1)
162 let data = "\"" + (plot.options.labels ?? []).joined(separator: "\" \"") + "\"\n"
163 + axes.map { "\"\($0.label)\" " + $0.fields.joined(separator: " ") }.joined(separator: "\n")
164 let settings = axes.map { "\"\($0.label)\" \($0.lowText) \($0.highText) \(radar.ticks == 0 ? 2 : radar.ticks)" }.joined(separator: "\n")
165 return "# Data\n$Data <<HEREHAVESOMEDATA\n\(data)\nHEREHAVESOMEDATA\nHeaderLines = 1\n\n"
166 + "# Settings for scale and offset adjustments\n# axis min max tics axisLabelXoff axisLabelYoff\n$Settings <<EOD\n\(settings)\nEOD\n"
167 }
168
169 /// `org--plot/radar-template` filled in.
170 static func radarScript(_ radar: Radar, setupFile: String) -> String {
171 let axis = radar.sharedTicks ? "1" : "$1"
172 let ticks = radar.ticks == 0 ? "" : """
173 '++' u (PosX($1,$2/TicCount)):(PosY($1,$2/TicCount)): \\
174 \t(PosX($1+1,$2/TicCount)-PosX($1,$2/TicCount)): \\
175 \t(PosY($1+1,$2/TicCount)-PosY($1,$2/TicCount)) w vec as 2 not, \\
176 '++' u (TicLabelPosX(\(axis),$2)):(TicLabelPosY(\(axis),$2)): \\
177 \t(sprintf('%g',TicValue(\(axis),$2))) w labels font ',8' @fgat not
178 """
179 return """
180 ### spider plot/chart with gnuplot
181 # also known as: radar chart, web chart, star chart, cobweb chart,
182 # radar plot, web plot, star plot, cobweb plot, etc. ...
183 set datafile separator ' '
184 set size square
185 unset tics
186 set angles degree
187 set key bmargin center horizontal
188 unset border
189
190 # Load data and setup
191 load "\(setupFile)"
192
193 # General settings
194 DataColCount = words($Data[1])-1
195 AxesCount = |$Data|-HeaderLines-1
196 AngleOffset = 90
197 Max = 1
198 d=0.1*Max
199 Direction = -1 # counterclockwise=1, clockwise = -1
200
201 # Tic settings
202 TicCount = \(radar.ticks == 0 ? 2 : radar.ticks)
203 TicOffset = 0.1
204 TicValue(axis,i) = real(i)*(word($Settings[axis],3)-word($Settings[axis],2)) \\
205 \t / word($Settings[axis],4)+word($Settings[axis],2)
206 TicLabelPosX(axis,i) = PosX(axis,i/TicCount) + PosY(axis, TicOffset)
207 TicLabelPosY(axis,i) = PosY(axis,i/TicCount) - PosX(axis, TicOffset)
208 TicLen = 0.03
209 TicdX(axis,i) = 0.5*TicLen*cos(alpha(axis)-90)
210 TicdY(axis,i) = 0.5*TicLen*sin(alpha(axis)-90)
211
212 # Label
213 LabOffset = 0.10
214 LabX(axis) = PosX(axis+1,Max+2*d) + PosY(axis, LabOffset)
215 LabY(axis) = PosY($0+1,Max+2*d)
216
217 # Functions
218 alpha(axis) = (axis-1)*Direction*360.0/AxesCount+AngleOffset
219 PosX(axis,R) = R*cos(alpha(axis))
220 PosY(axis,R) = R*sin(alpha(axis))
221 Scale(axis,value) = real(value-word($Settings[axis],2))/(word($Settings[axis],3)-word($Settings[axis],2))
222
223 # Spider settings
224 set style arrow 1 dt 1 lw 1.0 @fgal head filled size 0.06,25 # style for axes
225 set style arrow 2 dt 2 lw 0.5 @fgal nohead # style for weblines
226 set style arrow 3 dt 1 lw 1 @fgal nohead # style for axis tics
227 set samples AxesCount
228 set isosamples TicCount
229 set urange[1:AxesCount]
230 set vrange[1:TicCount]
231 set style fill transparent solid 0.2
232
233 set xrange[-Max-4*d:Max+4*d]
234 set yrange[-Max-4*d:Max+4*d]
235 plot \\
236 '+' u (0):(0):(PosX($0,Max+d)):(PosY($0,Max+d)) w vec as 1 not, \\
237 $Data u (LabX($0)): \\
238 \t(LabY($0)):1 every ::HeaderLines w labels center enhanced @fgt not, \\
239 for [i=1:DataColCount] $Data u (PosX($0+1,Scale($0+1,column(i+1)))): \\
240 \t(PosY($0+1,Scale($0+1,column(i+1)))) every ::HeaderLines w filledcurves lt i title word($Data[1],i+1), \\
241 \(ticks)
242 # '++' u (PosX($1,$2/TicCount)-TicdX($1,$2/TicCount)): \\
243 # (PosY($1,$2/TicCount)-TicdY($1,$2/TicCount)): \\
244 # (2*TicdX($1,$2/TicCount)):(2*TicdY($1,$2/TicCount)) \\
245 # w vec as 3 not, \\
246 ### end of code
247
248 """
249 }
250}
Sources/OrgPrograms/Gnuplot.swift +3 −1
@@ -22,7 +22,9 @@ extension PlotOutput {
22 if plot.options.file == nil { plot.options.values["file"] = .string(output.path) } 22 if plot.options.file == nil { plot.options.values["file"] = .string(output.path) }
23 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot), []) 23 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot), [])
24 try data.write(to: dataFile, atomically: true, encoding: .utf8) 24 try data.write(to: dataFile, atomically: true, encoding: .utf8)
25 var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels) 25 let setupFile = folder.appendingPathComponent("setup.gp")
26 if plot.options.type == "radar", plot.options["script"] == nil { try TablePlot.radarSetup(plot).write(to: setupFile, atomically: true, encoding: .utf8) }
27 var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, setupFile: setupFile.path)
26 if let custom = plot.options["script"]?.description { 28 if let custom = plot.options["script"]?.description {
27 let path = OrgPaths.expandingTilde(custom) 29 let path = OrgPaths.expandingTilde(custom)
28 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path) 30 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path)
Sources/Orgstar/ContentView.swift +5 −3
@@ -970,18 +970,20 @@ struct ContentView: View {
970 guard reach([url.path]) else { return } 970 guard reach([url.path]) else { return }
971 do { 971 do {
972 try PlotOutput.write(plot, to: url) 972 try PlotOutput.write(plot, to: url)
973 plotWritten(url, editor: editor) 973 plotWritten(url, editor: editor, note: PlotOutput.note(plot))
974 } catch { 974 } catch {
975 commands.show("\(error)") 975 commands.show("\(error)")
976 } 976 }
977 } else { 977 } else {
978 do { try PlotOutput.check(plot) } catch { return commands.show("\(error)") }
978 panel = .plot(UUID(), plot) 979 panel = .plot(UUID(), plot)
980 if let note = PlotOutput.note(plot) { commands.show(note) }
979 } 981 }
980 } 982 }
981 983
982 /// The image is where `file:` says; a link to it shows it again. 984 /// The image is where `file:` says; a link to it shows it again.
983 private func plotWritten(_ url: URL, editor: OrgEditor) { 985 private func plotWritten(_ url: URL, editor: OrgEditor, note: String? = nil) {
984 commands.show("Plot written to \(url.lastPathComponent)") 986 commands.show("Plot written to \(url.lastPathComponent)" + (note.map { ". " + $0 } ?? ""))
985 if editor.showsImages { editor.refreshImages() } 987 if editor.showsImages { editor.refreshImages() }
986 } 988 }
987 989
Sources/OrgstarMobile/EditorScreen.swift +3 −1
@@ -614,10 +614,12 @@ extension EditorScreen {
614 let plot = try TablePlot.plot(context.text, at: context.caret) 614 let plot = try TablePlot.plot(context.text, at: context.caret)
615 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) { 615 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
616 try PlotOutput.write(plot, to: url) 616 try PlotOutput.write(plot, to: url)
617 message = "Plot written to \(url.lastPathComponent)" 617 message = "Plot written to \(url.lastPathComponent)" + (PlotOutput.note(plot).map { ". " + $0 } ?? "")
618 if editor.showsImages { editor.restyleAll() } 618 if editor.showsImages { editor.restyleAll() }
619 } else { 619 } else {
620 try PlotOutput.check(plot)
620 sheet = .plot(plot) 621 sheet = .plot(plot)
622 if let note = PlotOutput.note(plot) { message = note }
621 } 623 }
622 } catch { 624 } catch {
623 message = "\(error)" 625 message = "\(error)"
Tests/OrgAppTests/PlotChartTests.swift +161 −1
@@ -1,3 +1,4 @@
1import Charts
1import Foundation 2import Foundation
2import OrgCore 3import OrgCore
3@testable import OrgApp 4@testable import OrgApp
@@ -13,6 +14,9 @@ struct PlotChartTests {
13 "#+PLOT: ind:1 with:histograms file:\"b.jpg\"\n| name | n |\n|------+---|\n| a | 3 |\n| b | 5 |\n", 14 "#+PLOT: ind:1 with:histograms file:\"b.jpg\"\n| name | n |\n|------+---|\n| a | 3 |\n| b | 5 |\n",
14 "#+PLOT: type:grid ind:1 file:\"c.pdf\"\n| r | a | b |\n|---+---+---|\n| x | 1 | 2 |\n| y | 3 | 4 |\n", 15 "#+PLOT: type:grid ind:1 file:\"c.pdf\"\n| r | a | b |\n|---+---+---|\n| x | 1 | 2 |\n| y | 3 | 4 |\n",
15 "#+PLOT: type:3d file:\"d.png\"\n| 1 | 2 | 3 |\n| 2 | 4 | 6 |\n| 3 | 6 | 9 |\n", 16 "#+PLOT: type:3d file:\"d.png\"\n| 1 | 2 | 3 |\n| 2 | 4 | 6 |\n| 3 | 6 | 9 |\n",
17 "#+PLOT: ind:1 with:linespoints file:\"h.png\" set:\"grid\" set:\"xlabel 'x'\" set:\"ylabel 'y'\" set:\"key left top\" set:\"logscale y\"\n| x | a | b |\n|---+---+---|\n| 1 | 2 | 30 |\n| 2 | 4 | 10 |\n| 3 | 3 | 500 |\n",
18 "#+PLOT: ind:1 with:linespoints file:\"h.svg\" set:\"grid\" set:\"xlabel 'x'\" set:\"ylabel 'y'\" set:\"key left top\" set:\"logscale y\"\n| x | a | b |\n|---+---+---|\n| 1 | 2 | 30 |\n| 2 | 4 | 10 |\n| 3 | 3 | 500 |\n",
19 "#+PLOT: type:radar file:\"r.png\"\n| skill | Anna | Ben |\n|---+---+---|\n| Swift | 7 | 4 |\n| Lisp | 3 | 8 |\n| SQL | 6 | 2 |\n| Ops | 8 | 1 |\n",
16 ] 20 ]
17 for text in texts { 21 for text in texts {
18 let plot = try TablePlot.plot(text, at: (text as NSString).range(of: "|").location) 22 let plot = try TablePlot.plot(text, at: (text as NSString).range(of: "|").location)
@@ -26,7 +30,163 @@ struct PlotChartTests {
26 } 30 }
27 } 31 }
28 let svg = try TablePlot.plot("#+PLOT: file:\"e.svg\"\n| 1 | 2 |\n", at: 25) 32 let svg = try TablePlot.plot("#+PLOT: file:\"e.svg\"\n| 1 | 2 |\n", at: 25)
29 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(svg, to: PlotOutput.file(svg, directory: folder)!) } 33 try PlotOutput.write(svg, to: PlotOutput.file(svg, directory: folder)!)
34 #expect(try String(contentsOf: folder.appendingPathComponent("e.svg"), encoding: .utf8).hasPrefix("<svg"))
35 let grid = try TablePlot.plot("#+PLOT: type:grid file:\"f.svg\"\n| 1 | 2 |\n| 3 | 4 |\n", at: 35)
36 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(grid, to: PlotOutput.file(grid, directory: folder)!) }
37 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(grid, to: folder.appendingPathComponent("g.eps")) }
38 }
39
40 static func plot(_ text: String) throws -> TablePlot.Plot {
41 try TablePlot.plot(text, at: (text as NSString).range(of: "\n|").location + 1)
42 }
43
44 static let table = "| x | a | b |\n|---+---+---|\n| 1 | 2 | 30 |\n| 2 | 4 | 10 |\n| 3 | 3 | 50 |\n"
45
46 @Test func followsTheSetSubset() throws {
47 let sets = ["title 'Set'", "xlabel 'Day'", "ylabel 'Count'", "xrange [0:10]", "yrange [*:60]",
48 "grid", "key left top", "xtics 2", "ytics 0.5"]
49 let plot = try Self.plot("#+PLOT: title:\"Given\" ind:1 " + sets.map { "set:\"\($0)\"" }.joined(separator: " ") + "\n" + Self.table)
50 let s = TablePlot.settings(plot)
51 #expect(s.title == "Set" && s.xlabel == "Day" && s.ylabel == "Count")
52 #expect(s.xrange?.low == 0 && s.xrange?.high == 10 && s.yrange?.low == nil && s.yrange?.high == 60)
53 #expect(!s.logY && !s.logX && s.grid && s.xtics == 2 && s.ytics == 0.5)
54 #expect(s.key == .at(vertical: "top", horizontal: "left"))
55 #expect(s.unfollowed.isEmpty && PlotOutput.note(plot) == nil)
56
57 #expect(TablePlot.settings(try Self.plot("#+PLOT: set:\"logscale\"\n" + Self.table)).logX)
58 #expect(TablePlot.settings(try Self.plot("#+PLOT: set:\"logscale y\"\n" + Self.table)).logY)
59 #expect(TablePlot.settings(try Self.plot("#+PLOT: set:\"key off\"\n" + Self.table)).key == .off)
60 #expect(TablePlot.settings(try Self.plot("#+PLOT: line:\"set key bottom\"\n" + Self.table)).key == .at(vertical: "bottom", horizontal: nil))
61 // gnuplot reads title:, then line:, then set:, so a set: wins.
62 #expect(TablePlot.settings(try Self.plot("#+PLOT: line:\"set title 'L'\" set:\"title 'S'\"\n" + Self.table)).title == "S")
63 }
64
65 @Test func reportsWhatItDoesntFollow() throws {
66 let plot = try Self.plot("#+PLOT: ind:1 script:\"plot.gp\" line:\"plot sin(x)\" set:\"style fill solid\" set:\"xrange [a:b]\" set:\"grid\"\n" + Self.table)
67 #expect(TablePlot.settings(plot).unfollowed == ["line:\"plot sin(x)\"", "set:\"style fill solid\"", "set:\"xrange [a:b]\"", "script:\"plot.gp\""])
68 #expect(PlotOutput.note(plot) == "Not followed without gnuplot: line:\"plot sin(x)\", set:\"style fill solid\", set:\"xrange [a:b]\", script:\"plot.gp\"")
69 // Text on the x axis has no range or steps; a heat map has no log scale; a radar plot sets its own key.
70 let text = try Self.plot("#+PLOT: ind:1 set:\"xtics 2\" set:\"ytics 2\"\n| n | v |\n|---+---|\n| a | 1 |\n| b | 2 |\n")
71 #expect(TablePlot.settings(text).unfollowed == ["set:\"xtics 2\""])
72 let grid = try Self.plot("#+PLOT: type:grid set:\"logscale\" set:\"xlabel 'C'\"\n| 1 | 2 |\n| 3 | 4 |\n")
73 #expect(TablePlot.settings(grid).unfollowed == ["set:\"logscale\""] && TablePlot.settings(grid).xlabel == "C")
74 // gnuplot's key leaves a heat map's colour scale alone.
75 let heat = try Self.plot("#+PLOT: type:grid set:\"key off\"\n| 1 | 2 |\n| 3 | 4 |\n")
76 #expect(TablePlot.settings(heat).unfollowed == ["set:\"key off\""] && TablePlot.settings(heat).key == nil)
77 let map = try Self.plot("#+PLOT: type:3d map:t set:\"key left\"\n| 1 | 2 |\n| 3 | 4 |\n")
78 #expect(TablePlot.settings(map).unfollowed == ["set:\"key left\""])
79 // On a log axis gnuplot's step is a factor, whichever comes first.
80 let logTics = try Self.plot("#+PLOT: ind:1 set:\"ytics 2\" set:\"logscale y\" set:\"xtics 1\"\n" + Self.table)
81 #expect(TablePlot.settings(logTics).unfollowed == ["set:\"ytics 2\""] && TablePlot.settings(logTics).ytics == nil && TablePlot.settings(logTics).xtics == 1)
82 let logX = try Self.plot("#+PLOT: ind:1 line:\"set xtics 2\" set:\"logscale x\"\n" + Self.table)
83 #expect(TablePlot.settings(logX).unfollowed == ["line:\"set xtics 2\""])
84 // gnuplot reverses an axis whose range runs high to low.
85 let reversed = try Self.plot("#+PLOT: ind:1 set:\"xrange [10:0]\" set:\"yrange [5:0]\" set:\"yrange [0:5]\"\n" + Self.table)
86 #expect(TablePlot.settings(reversed).unfollowed == ["set:\"xrange [10:0]\"", "set:\"yrange [5:0]\""] && TablePlot.settings(reversed).xrange == nil)
87 let radar = try Self.plot("#+PLOT: type:radar ticks:2 set:\"key off\" set:\"title 'R'\"\n| n | a |\n|---+---|\n| x | 1 |\n| y | 2 |\n| z | 3 |\n")
88 #expect(TablePlot.settings(radar).unfollowed == ["set:\"key off\""] && TablePlot.settings(radar).title == "R")
89 }
90
91 @Test func drawsRadarPlots() throws {
92 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-radar-\(UUID().uuidString)")
93 defer { try? FileManager.default.removeItem(at: folder) }
94 let plot = try Self.plot("#+PLOT: type:radar title:\"Skills\"\n| skill | Anna | Ben |\n|---+---+---|\n| Swift | 7 | 4 |\n| Lisp | 3 | 8 |\n| SQL | 6 | 2 |\n| Ops | 8 | 1 |\n")
95 for name in ["radar.png", "radar.pdf"] {
96 try PlotOutput.write(plot, to: folder.appendingPathComponent(name))
97 let size = (try FileManager.default.attributesOfItem(atPath: folder.appendingPathComponent(name).path)[.size] as? Int) ?? 0
98 #expect(size > 1000, "\(name) is \(size) bytes")
99 }
100 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(plot, to: folder.appendingPathComponent("radar.svg")) }
101 // With script:, TablePlot.plot leaves the radar to gnuplot; drawn here, it's refused.
102 let scripted = try Self.plot("#+PLOT: type:radar script:\"r.gp\"\n| n | a | b |\n|---+---+---|\n| x | 1 | 1 |\n| y | 2 | 3 |\n")
103 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.check(scripted) }
104 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(scripted, to: folder.appendingPathComponent("scripted.png")) }
105 #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("scripted.png").path))
106 try PlotOutput.check(plot)
107 }
108
109 @Test func refusesLogRangesAndDrawsLogBars() throws {
110 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-log-\(UUID().uuidString)")
111 defer { try? FileManager.default.removeItem(at: folder) }
112 let data = "| 1 | 3 |\n| 2 | 4 |\n"
113 for options in ["set:\"logscale y\" set:\"yrange [0:100]\"", "set:\"logscale x\" set:\"xrange [0:10]\"",
114 "set:\"logscale y\" set:\"yrange [-1:100]\"", "set:\"logscale y\" ymin:0", "set:\"logscale x\" xmin:-1"] {
115 let plot = try Self.plot("#+PLOT: ind:1 \(options)\n" + data)
116 #expect(throws: PlotOutput.Failure.self, "\(options)") { try PlotOutput.check(plot) }
117 for name in ["o.png", "o.pdf"] {
118 #expect(throws: PlotOutput.Failure.self, "\(options)") { try PlotOutput.write(plot, to: folder.appendingPathComponent(name)) }
119 }
120 }
121 for options in ["with:boxes set:\"logscale y\"", "with:impulses set:\"logscale y\"", "with:histograms set:\"logscale y\"",
122 "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\""] {
123 let plot = try Self.plot("#+PLOT: ind:1 \(options)\n| 1 | 1 |\n| 2 | 5 |\n")
124 for name in ["b.png", "b.pdf"] {
125 let url = folder.appendingPathComponent(name)
126 try PlotOutput.write(plot, to: url)
127 let size = (try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0
128 #expect(size > 1000, "\(options) \(name) is \(size) bytes")
129 }
130 }
131 }
132
133 @Test func skipsLogPointsPastADouble() throws {
134 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-log-\(UUID().uuidString)")
135 defer { try? FileManager.default.removeItem(at: folder) }
136 for axis in ["x", "y"] {
137 for field in ["1e400", "3e-324", "1e-320", "1.5e308", "1.0e+INF"] {
138 let row = axis == "x" ? "| \(field) | 5 |" : "| 2 | \(field) |"
139 let plot = try Self.plot("#+PLOT: ind:1 set:\"logscale \(axis)\"\n| x | y |\n|---+---|\n| 1 | 10 |\n\(row)\n| 3 | 20 |\n")
140 try PlotOutput.check(plot)
141 let svg = try TablePlot.svg(plot)
142 #expect(!svg.contains("inf") && !svg.contains("nan"), "\(axis) \(field)")
143 try PlotOutput.write(plot, to: folder.appendingPathComponent("l.png"))
144 }
145 }
146 for range in ["[1:1e400]", "[1e-320:10]"] {
147 let plot = try Self.plot("#+PLOT: ind:1 set:\"logscale y\" set:\"yrange \(range)\"\n| 1 | 10 |\n| 2 | 20 |\n")
148 #expect(throws: PlotOutput.Failure.self, "\(range)") { try PlotOutput.check(plot) }
149 }
150 }
151
152 @Test func placesALoneKeyDirectionAsGnuplot() throws {
153 func position(_ set: String) throws -> String {
154 String(describing: PlotChart.keyPosition(TablePlot.settings(try Self.plot("#+PLOT: set:\"\(set)\"\n" + Self.table)).key))
155 }
156 #expect(try position("key top") == String(describing: AnnotationPosition.topTrailing))
157 #expect(try position("key left") == String(describing: AnnotationPosition.topLeading))
158 #expect(try position("key bottom") == String(describing: AnnotationPosition.bottomTrailing))
159 #expect(try position("key right") == String(describing: AnnotationPosition.topTrailing))
160 #expect(try position("key bottom left") == String(describing: AnnotationPosition.bottomLeading))
161 }
162
163 @Test func capsRadarRingsWithoutGnuplot() throws {
164 let plot = try Self.plot("#+PLOT: type:radar ticks:2000\n| n | a | b |\n|---+---+---|\n| x | 1 | 5 |\n| y | 2 | 3 |\n")
165 #expect(try TablePlot.radarSetup(plot).hasSuffix(" 2000\nEOD\n"))
166 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.check(plot) }
167 try PlotOutput.check(Self.plot("#+PLOT: type:radar ticks:1000\n| n | a | b |\n|---+---+---|\n| x | 1 | 5 |\n| y | 2 | 3 |\n"))
168 }
169
170 @Test func writesSVG() throws {
171 let lines = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"title 'T&C'\" set:\"xlabel 'Day'\" set:\"grid\"\n" + Self.table))
172 #expect(lines.hasPrefix("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"480\""))
173 #expect(lines.components(separatedBy: "<polyline").count - 1 == 2)
174 #expect(lines.contains(">T&amp;C</text>") && lines.contains(">Day</text>") && lines.contains("stroke-dasharray"))
175 #expect(lines.contains(">a</text>") && lines.contains(">b</text>"))
176 let bars = try TablePlot.svg(Self.plot("#+PLOT: ind:1 with:histograms set:\"key off\"\n| n | v |\n|---+---|\n| a | 3 |\n| b | 5 |\n"))
177 #expect(bars.components(separatedBy: "<rect x=").count - 1 == 2 + 2)
178 #expect(bars.contains(">a</text>") && !bars.contains(">v</text>") && !bars.contains("stroke-dasharray"))
179 let log = try TablePlot.svg(Self.plot("#+PLOT: ind:1 with:points set:\"logscale y\"\n| x | v |\n|---+---|\n| 1 | 5 |\n| 2 | 500 |\n| 3 | 0 |\n"))
180 #expect(log.contains(">1</text>") && log.contains(">1000</text>") && log.components(separatedBy: "<circle").count - 1 == 2)
181 // A log range with no power of ten in it is labelled at its ends.
182 let narrow = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"logscale y\" set:\"yrange [2:5]\"\n| 1 | 3 |\n| 2 | 4 |\n"))
183 #expect(narrow.contains(">2</text>") && narrow.contains(">5</text>"))
184 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"logscale y\"\n| 1 | 0 |\n| 2 | -4 |\n")) }
185 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"logscale y\" set:\"yrange [0:100]\"\n| 1 | 3 |\n| 2 | 4 |\n")) }
186 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"logscale x\" set:\"xrange [*:10]\"\n| 0 | 3 |\n| -1 | 4 |\n")) }
187 let ranged = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"xrange [0:10]\" set:\"ytics 25\"\n" + Self.table))
188 #expect(ranged.contains(">10</text>") && ranged.contains(">25</text>") && ranged.contains(">50</text>"))
189 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: type:3d\n| 1 | 2 |\n| 3 | 4 |\n")) }
30 } 190 }
31 191
32 @Test func interpolatesTheMatrix() { 192 @Test func interpolatesTheMatrix() {
Tests/OrgCoreTests/TablePlotTests.swift +118 −6
@@ -57,6 +57,49 @@ struct TablePlotTests {
57 | 1 | 2 | 57 | 1 | 2 |
58 | 3 | 4 | 58 | 3 | 4 |
59 """, 59 """,
60 """
61 #+PLOT: type:radar title:"Skills"
62 | skill | Anna | Ben | Cleo |
63 |--------+------+-----+------|
64 | Swift | 7 | 4 | 9 |
65 | Lisp | 3 | 8 | 5 |
66 | SQL | 6 | 6 | 2 |
67 | Design | 2.5 | 9 | 4 |
68 | Ops | 8 | 1 | 7 |
69 """,
70 """
71 #+PLOT: type:radar ymin:0 ymax:8
72 | axis | a | b |
73 |------+----+----|
74 | x | 1 | 9 |
75 | y | 4 | 4 |
76 | z | 8 | 3 |
77 """,
78 """
79 #+PLOT: type:radar ticks:0
80 | axis | a | b |
81 |------+-----+-----|
82 | p | 120 | 340 |
83 | q | 0.5 | 0.2 |
84 | r | 15 | 90 |
85 """,
86 """
87 #+PLOT: type:radar ticks:4 file:"/tmp/orgstar-radar.png"
88 | axis | a |
89 |------+----|
90 | one | 3 |
91 | two | 12 |
92 | three | 7 |
93 """,
94 """
95 #+PLOT: type:radar
96 | axis | a | b | c | d |
97 |------+------+------+-----+-----|
98 | u | 1 | 2 | 3 | 4 |
99 | v | 10 | 40 | 25 | 33 |
100 | w | 0.01 | 0.05 | 0.2 | 0.3 |
101 | x | 100 | 700 | 350 | 250 |
102 """,
60 ] 103 ]
61 104
62 static func lisp(_ s: String) -> String { 105 static func lisp(_ s: String) -> String {
@@ -64,7 +107,7 @@ struct TablePlotTests {
64 } 107 }
65 108
66 /// The script and the data file `org-plot/gnuplot` writes, gnuplot itself left out. 109 /// The script and the data file `org-plot/gnuplot` writes, gnuplot itself left out.
67 static func emacs(_ text: String, data: String) throws -> (script: String, data: String) { 110 static func emacs(_ text: String, data: String, setup: String = "") throws -> (script: String, data: String, setup: String) {
68 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)") 111 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)")
69 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 112 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
70 defer { try? FileManager.default.removeItem(at: folder) } 113 defer { try? FileManager.default.removeItem(at: folder) }
@@ -77,7 +120,8 @@ struct TablePlotTests {
77 (provide 'gnuplot) 120 (provide 'gnuplot)
78 (let ((captured nil)) 121 (let ((captured nil))
79 (cl-letf (((symbol-function 'gnuplot-send-buffer-to-gnuplot) (lambda () (setq captured (buffer-string)))) 122 (cl-letf (((symbol-function 'gnuplot-send-buffer-to-gnuplot) (lambda () (setq captured (buffer-string))))
80 ((symbol-function 'org-babel-temp-stable-file) (lambda (&rest _) \(lisp(data))))) 123 ((symbol-function 'org-babel-temp-stable-file) (lambda (&rest _) \(lisp(data))))
124 ((symbol-function 'make-temp-file) (lambda (&rest _) \(lisp(setup)))))
81 (with-temp-buffer 125 (with-temp-buffer
82 (insert \(lisp(text))) 126 (insert \(lisp(text)))
83 (org-mode) 127 (org-mode)
@@ -88,25 +132,64 @@ struct TablePlotTests {
88 """ 132 """
89 let log = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"]) 133 let log = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
90 guard let script = try? String(contentsOfFile: output, encoding: .utf8) else { throw EmacsOracle.EvaluateError(log: log) } 134 guard let script = try? String(contentsOfFile: output, encoding: .utf8) else { throw EmacsOracle.EvaluateError(log: log) }
91 return (script, (try? String(contentsOfFile: data, encoding: .utf8)) ?? "") 135 return (script, (try? String(contentsOfFile: data, encoding: .utf8)) ?? "", (try? String(contentsOfFile: setup, encoding: .utf8)) ?? "")
92 } 136 }
93 137
94 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: cases.indices) 138 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: cases.indices)
95 func scriptsAndDataMatchEmacs(index: Int) throws { 139 func scriptsAndDataMatchEmacs(index: Int) throws {
96 let text = Self.cases[index] 140 let text = Self.cases[index]
97 let dataFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-data-\(UUID().uuidString)").path 141 let dataFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-data-\(UUID().uuidString)").path
98 defer { try? FileManager.default.removeItem(atPath: dataFile) } 142 let setupFile = dataFile + "-setup"
99 let expected = try Self.emacs(text, data: dataFile) 143 defer { try? FileManager.default.removeItem(atPath: dataFile); try? FileManager.default.removeItem(atPath: setupFile) }
144 let expected = try Self.emacs(text, data: dataFile, setup: setupFile)
100 let offset = (text as NSString).range(of: "|").location 145 let offset = (text as NSString).range(of: "|").location
101 let plot = try TablePlot.plot(text, at: offset) 146 let plot = try TablePlot.plot(text, at: offset)
102 var utc = Calendar(identifier: .gregorian) 147 var utc = Calendar(identifier: .gregorian)
103 utc.timeZone = TimeZone(identifier: "UTC")! 148 utc.timeZone = TimeZone(identifier: "UTC")!
104 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot, calendar: utc), []) 149 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot, calendar: utc), [])
105 let script = TablePlot.script(plot, dataFile: dataFile, output: plot.options.file, yLabels: labels) 150 let script = TablePlot.script(plot, dataFile: dataFile, output: plot.options.file, yLabels: labels, setupFile: setupFile)
151 if plot.options.type == "radar" {
152 let setup = try TablePlot.radarSetup(plot)
153 #expect(setup == expected.setup, "case \(index)\nours:\n\(setup)\nemacs:\n\(expected.setup)")
154 }
106 #expect(script == expected.script, "case \(index)\nours:\n\(script)\nemacs:\n\(expected.script)") 155 #expect(script == expected.script, "case \(index)\nours:\n\(script)\nemacs:\n\(expected.script)")
107 #expect(data == expected.data, "case \(index)\nours:\n\(data.debugDescription)\nemacs:\n\(expected.data.debugDescription)") 156 #expect(data == expected.data, "case \(index)\nours:\n\(data.debugDescription)\nemacs:\n\(expected.data.debugDescription)")
108 } 157 }
109 158
159 /// `org--plot/sensible-tick-num` over tables of varied ranges; "error" where Emacs signals one.
160 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
161 func radarTicksMatchEmacs() throws {
162 var seed: UInt64 = 7
163 func next(_ n: Int) -> Int { seed = seed &* 6364136223846793005 &+ 1442695040888963407; return Int(seed >> 33) % n }
164 let scales = [1.0, 10, 100, 0.1, 1000, 3]
165 var tables: [[[String]]] = []
166 for _ in 0..<60 {
167 let scale = scales[next(scales.count)]
168 let rows = (0..<(2 + next(4))).map { r in
169 // Distinct values, so no axis is flat (Emacs never returns on one).
170 ["r\(r)"] + (0..<(2 + next(3))).map { c in TablePlot.printed((Double(next(50) * 10 + c) * scale / 10, scale >= 10)) }
171 }
172 tables.append(rows)
173 }
174 let forms = tables.map { t in
175 "(condition-case nil (format \"%S\" (org--plot/sensible-tick-num '(" + t.map { "(" + $0.map { Self.lisp($0) }.joined(separator: " ") + ")" }.joined(separator: " ") + "))) (error \"error\"))"
176 }
177 let expected = try EmacsOracle.evaluate("", "(progn (require 'org-plot) (list " + forms.joined(separator: " ") + "))")
178 #expect(Set(expected).count > 4 && expected.count == tables.count)
179 for (t, want) in zip(tables, expected) {
180 let ours = TablePlot.sensibleTicks(t, hardMin: nil, hardMax: nil).map(String.init) ?? "error"
181 #expect(ours == want, "\(t)")
182 }
183 let rows = [["a", "1", "5"], ["b", "3", "4"]]
184 let bounds: [(Double?, Double?, String)] = [(100, nil, "100 nil"), (nil, 0, "nil 0"), (0, 10, "0 10"), (-5, nil, "-5 nil")]
185 let hard = try EmacsOracle.evaluate("", "(progn (require 'org-plot) (list " + bounds.map {
186 "(condition-case nil (format \"%S\" (org--plot/sensible-tick-num '((\"a\" \"1\" \"5\") (\"b\" \"3\" \"4\")) \($0.2))) (error \"error\"))"
187 }.joined(separator: " ") + "))")
188 for (b, want) in zip(bounds, hard) {
189 #expect((TablePlot.sensibleTicks(rows, hardMin: b.0, hardMax: b.1).map(String.init) ?? "error") == want, "\(b.2)")
190 }
191 }
192
110 @Test func seriesAndMatrices() throws { 193 @Test func seriesAndMatrices() throws {
111 let plot = try TablePlot.plot(Self.cases[0], at: 100) 194 let plot = try TablePlot.plot(Self.cases[0], at: 100)
112 let series = TablePlot.series(plot) 195 let series = TablePlot.series(plot)
@@ -121,6 +204,35 @@ struct TablePlotTests {
121 let m = TablePlot.matrix(grid) 204 let m = TablePlot.matrix(grid)
122 #expect(m.values == [[1, 2], [3, 4]] && m.rowLabels == ["r1", "r2"]) 205 #expect(m.values == [[1, 2], [3, 4]] && m.rowLabels == ["r1", "r2"])
123 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| 1 |\n", at: 0) } 206 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| 1 |\n", at: 0) }
207 // Emacs never returns choosing ticks for an axis whose values are all the same.
208 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| a | 1 | 1 |\n| b | 2 | 3 |\n", at: 0) }
209 // Emacs signals an error where the ranges leave nothing to pick ticks from.
210 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ymin:0 ymax:10\n| a | 1 | 9 |\n| b | 2 | 3 |\n", at: 0) }
211 _ = try TablePlot.plot("#+PLOT: type:radar ticks:3\n| a | 1 | 1 |\n| b | 2 | 3 |\n", at: 0)
212 // A ymin above a row's values, or a ymax below them: Emacs signals overflow-error.
213 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ymin:100\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0) }
214 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ymax:0\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0) }
215 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ticks:-1\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0) }
216 // string-to-number reads the reader's infinities and NaNs; Emacs then signals overflow-error.
217 #expect(TablePlot.lispNumber("-2.0e+INF").value == -.infinity && TablePlot.lispNumber("1e+NaN").value.isNaN)
218 #expect(TablePlot.lispNumber("1.0e-INF").value == 1 && TablePlot.lispNumber("1.0e+inf").value == 1 && TablePlot.stringToNumber(".5e+INFx") == .infinity)
219 for field in ["1.0e+INF", "1.0e+NaN"] {
220 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ticks:4\n| a | 1 | \(field) |\n| b | 2 | 5 |\n", at: 0) }
221 }
222 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar ticks:99999999999999999999\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0) }
223 // gnuplot draws as many rings as it's given.
224 _ = try TablePlot.plot("#+PLOT: type:radar ticks:2000\n| x | 1 | 5 |\n| y | 2 | 3 |\n", at: 0)
225 // Emacs scales every row with or without ticks:, and signals overflow-error past a double.
226 for row in ["| x | 1e400 | 5 |", "| x | 1e400 | 1e400 |", "| x | -1e400 | 5 |", "| x | 1e308 | -1e308 |"] {
227 #expect(throws: TablePlot.Failure.self, "\(row)") { try TablePlot.plot("#+PLOT: type:radar ticks:3\n\(row)\n| y | 2 | 3 |\n", at: 0) }
228 #expect(throws: TablePlot.Failure.self, "\(row)") { try TablePlot.plot("#+PLOT: type:radar ticks:3 ymin:0 ymax:10\n\(row)\n| y | 2 | 3 |\n", at: 0) }
229 }
230 // Emacs prints a bignum as it is.
231 let big = try TablePlot.radarSetup(TablePlot.plot("#+PLOT: type:radar ticks:3\n| x | 100000000000000000000 | 100000000000000000000 |\n| y | -007 | -007 |\n", at: 0))
232 #expect(big.contains("\"x\" 100000000000000000000 100000000000000000000 3\n\"y\" -7 -7 3\n"), "\(big)")
233 let radar = try TablePlot.radar(TablePlot.plot(Self.cases[9], at: 40))
234 #expect(radar.series == ["a", "b"] && radar.axes.map(\.label) == ["x", "y", "z"] && radar.sharedTicks)
235 #expect(radar.axes[2].values == [8, 3] && radar.axes[0].low == 0 && radar.axes[0].high == 8)
124 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("no table\n", at: 0) } 236 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("no table\n", at: 0) }
125 } 237 }
126} 238}
docs/manual/guide/10-tables.org +35 −8
@@ -773,7 +773,7 @@ after it, as the =#+PLOT:= lines above it say:
773 773
774| Option | Meaning | 774| Option | Meaning |
775|------------+-----------------------------------------------------------------------------| 775|------------+-----------------------------------------------------------------------------|
776| =type= | =2d= (the default), =3d= or =grid= | 776| =type= | =2d= (the default), =3d=, =grid= or =radar= |
777| =ind= | The column of x values, counting from 1; 0 (the default) plots against row numbers | 777| =ind= | The column of x values, counting from 1; 0 (the default) plots against row numbers |
778| =deps= | The columns to plot, as a list such as =(2 3)=; all but =ind= by default | 778| =deps= | The columns to plot, as a list such as =(2 3)=; all but =ind= by default |
779| =with= | =lines= (the default), =points=, =linespoints=, =impulses=, =boxes=, =histograms=, =steps=, =fsteps= | 779| =with= | =lines= (the default), =points=, =linespoints=, =impulses=, =boxes=, =histograms=, =steps=, =fsteps= |
@@ -782,7 +782,7 @@ after it, as the =#+PLOT:= lines above it say:
782| =labels= | Names for the columns, as a list; a header row above a rule names them otherwise | 782| =labels= | Names for the columns, as a list; a header row above a rule names them otherwise |
783| =map= | With =t=, a =3d= plot is seen from above | 783| =map= | With =t=, a =3d= plot is seen from above |
784| =ymin=, =ymax=, =xmin=, =xmax= | The axes' ranges; =min= and =max= are =ymin= and =ymax= | 784| =ymin=, =ymax=, =xmin=, =xmax= | The axes' ranges; =min= and =max= are =ymin= and =ymax= |
785| =ticks= | How many marks the y axis has | 785| =ticks= | How many marks the y axis has; for =radar=, how many rings the web has |
786| =transpose= | With =yes=, rows become columns | 786| =transpose= | With =yes=, rows become columns |
787| =set=, =line=, =script=, =timefmt= | gnuplot commands, a line of gnuplot, a gnuplot script file and the time format, for gnuplot | 787| =set=, =line=, =script=, =timefmt= | gnuplot commands, a line of gnuplot, a gnuplot script file and the time format, for gnuplot |
788 788
@@ -791,19 +791,46 @@ a longer word (=timeind:t= sets =ind=), an unquoted value ends at a =.=, =,= or
791options before the last =line:= are dropped, and each =set:= and =line:= that's kept comes 791options before the last =line:= are dropped, and each =set:= and =line:= that's kept comes
792twice, as Org reads the options twice. An ind column of timestamps is plotted as dates, and one of text as labels. 792twice, as Org reads the options twice. An ind column of timestamps is plotted as dates, and one of text as labels.
793 793
794A =radar= plot draws each row as an axis, clockwise from the top, and each column after
795the first as a series named by the header. Each axis is scaled from its row's lowest and
796highest values rounded outward (120 to 340 becomes 100 to 400), or from =ymin= to =ymax=. Org
797works out the number of rings from the values; where Org can't (it signals an error, as for a
798=ymin= above a row's values, or never finishes, as for a row whose values are all the same),
799orgstar reports it and asks for =ticks:=. =ticks:= can't be below 0, and without gnuplot it
800takes at most 1000. A row whose values or their range overflow a double is refused, as Emacs signals an
801error for it.
802
794On the Mac, when gnuplot is installed (orgstar looks on the same =PATH= as code blocks), the 803On the Mac, when gnuplot is installed (orgstar looks on the same =PATH= as code blocks), the
795table goes to gnuplot as Emacs sends it: the same data file and script, so every option and 804table goes to gnuplot as Emacs sends it: the same data file and script, so every option and
796gnuplot's own terminals and styles apply. A plot without =file:= is drawn to an image and shown 805gnuplot's own terminals and styles apply. A plot without =file:= is drawn to an image and shown
797in a sheet. Without gnuplot, and on iOS, orgstar draws the plot itself with Swift Charts: =2d= 806in a sheet. Without gnuplot, and on iOS, orgstar draws the plot itself with Swift Charts: =2d=
798as lines, points or bars by =with:=, =grid= as a heat map, =3d= as a surface (a wireframe in a 807as lines, points or bars by =with:=, =grid= as a heat map, =3d= as a surface (a wireframe in a
799file). =file:= then takes =.png=, =.jpg= or =.pdf=, 640 by 480 points as gnuplot's default; the 808file), =radar= as a web. =file:= then takes =.png=, =.jpg= or =.pdf=, 640 by 480 points as
800gnuplot-only options are ignored. If inline images are showing, a link to the file shows the 809gnuplot's default, or =.svg= for a =2d= plot. A log axis places values from 1e-307 to
801new plot. 8101e308 and leaves out others; it needs at least one, and its range, if given, must lie
802 811within them. If inline images are showing, a link to the file
803=type:radar= needs gnuplot; orgstar reports it. 812shows the new plot.
813
814Without gnuplot these =set:= commands are followed, also as a =line:= that starts with =set=:
815
816| Command | Effect |
817|----------------------------------------+-------------------------------------------------------------------------|
818| =title 'T'= | The title, over =title:= |
819| =xlabel 'X'=, =ylabel 'Y'= | The axes' names |
820| =xrange [0:10]=, =yrange [*:5]= | The axes' ranges, low to high; =*= or nothing leaves an end to the data |
821| =logscale=, =logscale x=, =logscale y= | Logarithmic axes |
822| =grid= | Grid lines at the marks |
823| =key off=, =key top left= | Hides or places the legend (top, bottom, left, right; else top right) |
824| =xtics 2=, =ytics 0.5= | A mark every so many units, on an axis that isn't logarithmic |
825
826=2d= plots follow all of them, except that an x axis of text or dates takes no range, steps or
827log scale. =grid= and =3d map:t= plots follow the title and axis names; other =3d= plots
828and =radar= plots only the title. Other commands, other =line:= options and =script:= are left
829out, and the message after plotting names them, such as =Not followed without gnuplot:
830set:"style fill solid"=.
804 831
805The [[file:../install.org][Mac App Store version]] doesn't use gnuplot: it always draws 832The [[file:../install.org][Mac App Store version]] doesn't use gnuplot: it always draws
806the plot with Swift Charts, and reports =type:radar= in the same way. 833the plot itself in the same way.
807 834
808* On iOS 835* On iOS
809 836
docs/manual/install.org +1 −1
@@ -58,7 +58,7 @@ App Store version.
58| Sessions, graphics | JavaScript sessions; no graphics | Yes | 58| Sessions, graphics | JavaScript sessions; no graphics | Yes |
59| Tangling | Yes | Yes | 59| Tangling | Yes | Yes |
60| Table formulas | Those orgstar computes itself | The rest in Emacs as well | 60| Table formulas | Those orgstar computes itself | The rest in Emacs as well |
61| Plots | Drawn with Swift Charts | gnuplot when installed, else Swift Charts | 61| Plots | Drawn with Swift Charts, following a subset of gnuplot's =set= | gnuplot when installed, else Swift Charts |
62| Export | HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX, ASCII; publishing | Also PDF through LaTeX, in Emacs | 62| Export | HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX, ASCII; publishing | Also PDF through LaTeX, in Emacs |
63| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= | 63| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= |
64| Files outside your folders | After you grant access to their folder | Directly | 64| Files outside your folders | After you grant access to their folder | Directly |