Commit c27e8a552f

c27e8a552fc7f0bf0908e978ab84db99f1df5400

parent: dd4ac706e9

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 08:58 UTC

Draw radar plots, follow a subset of set:, write SVG without gnuplot

Layout: unified · split

Sources/OrgApp/PlotChart.swift +161 −22
@@ -5,7 +5,8 @@ import SwiftUI
55
66/// A `#+PLOT` table drawn by Swift Charts, as gnuplot would draw it for org-plot: 2d as lines,
77/// 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.
910public struct PlotChart: View {
1011 let plot: TablePlot.Plot
1112 let still: Bool
@@ -16,33 +17,47 @@ public struct PlotChart: View {
1617 }
1718
1819 public var body: some View {
20 let settings = TablePlot.settings(plot)
1921 VStack(spacing: 8) {
20 if let title = plot.options.title { Text(title).font(.headline) }
22 if let title = settings.title { Text(title).font(.headline) }
2123 switch plot.options.type {
22 case "grid": HeatMap(plot: plot)
23 case "3d" where plot.options["map"]?.truthy == true: HeatMap(plot: plot)
24 case "grid": HeatMap(plot: plot, settings: settings)
25 case "3d" where plot.options["map"]?.truthy == true: HeatMap(plot: plot, settings: settings)
2426 case "3d" where still: Wireframe(values: TablePlot.matrix(plot).values)
2527 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)
2730 }
2831 }
2932 .padding()
3033 }
3134
32 /// The `ymin`/`ymax` (or `xmin`/`xmax`) range, filling in from `values` what isn't given.
33 static func domain(_ low: TablePlot.Value?, _ high: TablePlot.Value?, values: [Double]) -> ClosedRange<Double>? {
34 func number(_ v: TablePlot.Value?) -> Double? { if case .number(let n)? = v { n } else { nil } }
35 guard number(low) != nil || number(high) != nil else { return nil }
36 let lower = number(low) ?? values.min() ?? 0
37 let upper = number(high) ?? values.max() ?? lower + 1
35 /// The range given by `set` or the options, filling in from `values` what isn't given.
36 static func domain(_ low: Double?, _ high: Double?, values: [Double]) -> ClosedRange<Double>? {
37 guard low != nil || high != nil else { return nil }
38 let lower = low ?? values.min() ?? 0
39 let upper = high ?? values.max() ?? lower + 1
3840 return lower < upper ? lower...upper : nil
3941 }
4042
43 static func number(_ v: TablePlot.Value?) -> Double? { if case .number(let n)? = v { n } else { nil } }
44
4145 struct Lines: View {
4246 let plot: TablePlot.Plot
47 let settings: TablePlot.Settings
4348
4449 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, point.y <= 0 { return true }
56 if s.logX, case .number(let n) = point.x, n <= 0 { return true }
57 return false
58 }
59 return series
60 }
4661 let o = plot.options
4762 let ys = series.flatMap { $0.points.map(\.y) }
4863 let xs = series.flatMap { $0.points.compactMap { if case .number(let n) = $0.x { n } else { nil } } }
@@ -56,20 +71,36 @@ public struct PlotChart: View {
5671 }
5772 }
5873 }
59 .chartYAxis { AxisMarks(values: .automatic(desiredCount: ticks ?? 5)) }
60 .chartLegend(series.count > 1 ? .visible : .hidden)
74 .chartXAxis {
75 AxisMarks(values: s.xtics.map { AxisMarkValues.stride(by: $0) } ?? .automatic) { _ in
76 if s.grid { AxisGridLine() }
77 AxisTick()
78 AxisValueLabel()
79 }
80 }
81 .chartYAxis {
82 AxisMarks(values: s.ytics.map { AxisMarkValues.stride(by: $0) } ?? .automatic(desiredCount: ticks ?? 5)) { _ in
83 if s.grid { AxisGridLine() }
84 AxisTick()
85 AxisValueLabel()
86 }
87 }
88 .chartXAxisLabel { if let label = s.xlabel { Text(label) } }
89 .chartYAxisLabel { if let label = s.ylabel { Text(label) } }
90 .key(s.key, shown: series.count > 1)
6191 // As gnuplot autoscales: to the data, from zero for bars.
92 let yType: ScaleType? = s.logY ? .log : nil, xType: ScaleType? = s.logX ? .log : nil
6293 let y = Group {
63 if let domain = PlotChart.domain(o["ymin"], o["ymax"], values: ys) {
64 chart.chartYScale(domain: domain)
94 if let domain = PlotChart.domain(s.yrange?.low ?? PlotChart.number(o["ymin"]), s.yrange?.high ?? PlotChart.number(o["ymax"]), values: ys) {
95 chart.chartYScale(domain: domain, type: yType)
6596 } else {
66 chart.chartYScale(domain: .automatic(includesZero: bars))
97 chart.chartYScale(domain: .automatic(includesZero: bars && !s.logY), type: yType)
6798 }
6899 }
69 if numericX, let domain = PlotChart.domain(o["xmin"], o["xmax"], values: xs) {
70 y.chartXScale(domain: domain)
100 if numericX, let domain = PlotChart.domain(s.xrange?.low ?? PlotChart.number(o["xmin"]), s.xrange?.high ?? PlotChart.number(o["xmax"]), values: xs) {
101 y.chartXScale(domain: domain, type: xType)
71102 } else if numericX {
72 y.chartXScale(domain: .automatic(includesZero: false))
103 y.chartXScale(domain: .automatic(includesZero: false), type: xType)
73104 } else {
74105 y
75106 }
@@ -107,6 +138,7 @@ public struct PlotChart: View {
107138
108139 struct HeatMap: View {
109140 let plot: TablePlot.Plot
141 let settings: TablePlot.Settings
110142
111143 var body: some View {
112144 let (values, rowLabels) = TablePlot.matrix(plot)
@@ -124,6 +156,9 @@ public struct PlotChart: View {
124156 // The first row at the bottom, as gnuplot draws it.
125157 .chartYScale(domain: values.indices.reversed().map { rowName($0, rowLabels) })
126158 .chartXScale(domain: columnLabels)
159 .chartXAxisLabel { if let label = settings.xlabel { Text(label) } }
160 .chartYAxisLabel { if let label = settings.ylabel { Text(label) } }
161 .key(settings.key, shown: true)
127162 }
128163
129164 func rowName(_ r: Int, _ labels: [String]) -> String { r < labels.count ? labels[r] : "\(r + 1)" }
@@ -165,6 +200,98 @@ public struct PlotChart: View {
165200 }
166201}
167202
203extension View {
204 /// The legend as `set key` places it, else shown or not.
205 func key(_ key: TablePlot.Settings.Key?, shown: Bool) -> some View {
206 var position = AnnotationPosition.automatic
207 if case .at(let vertical, let horizontal) = key {
208 switch (vertical, horizontal) {
209 case ("top", "left"): position = .topLeading
210 case ("top", "right"): position = .topTrailing
211 case ("bottom", "left"): position = .bottomLeading
212 case ("bottom", "right"): position = .bottomTrailing
213 case ("top", _): position = .top
214 case ("bottom", _): position = .bottom
215 case (_, "left"): position = .leading
216 case (_, "right"): position = .trailing
217 default: break
218 }
219 }
220 let visible = key.map { $0 != .off } ?? shown
221 return chartLegend(visible ? .visible : .hidden).chartLegend(position: position)
222 }
223}
224
225/// A radar plot as org-plot's gnuplot script draws it: an axis per row, clockwise from the
226/// top, each scaled from its low to its high value; a web at each tick; each series filled.
227struct Radar: View {
228 let radar: TablePlot.Radar
229
230 var body: some View {
231 VStack(spacing: 8) {
232 Canvas { context, size in
233 let n = radar.axes.count
234 guard n > 0 else { return }
235 let center = CGPoint(x: size.width / 2, y: size.height / 2)
236 // gnuplot's range is 1.4 times the axes' length each way.
237 let unit = min(size.width, size.height) / 2 / 1.4
238 func point(_ axis: Int, _ r: Double, offset: Double = 0) -> CGPoint {
239 let angle = (90 - Double(axis) * 360 / Double(n)) * .pi / 180
240 return CGPoint(x: center.x + (r * cos(angle) + offset * sin(angle)) * unit,
241 y: center.y - (r * sin(angle) - offset * cos(angle)) * unit)
242 }
243 let count = radar.ticks == 0 ? 2 : radar.ticks
244 if radar.ticks != 0 {
245 for i in 1...count {
246 let r = Double(i) / Double(count)
247 var web = Path()
248 web.move(to: point(0, r))
249 for axis in 1...n { web.addLine(to: point(axis % n, r)) }
250 context.stroke(web, with: .color(.secondary), style: StrokeStyle(lineWidth: 0.5, dash: [3, 3]))
251 for axis in 0..<n {
252 let scale = radar.axes[radar.sharedTicks ? 0 : axis]
253 let value = Double(i) * (scale.high - scale.low) / Double(count) + scale.low
254 context.draw(Text(String(format: "%g", value)).font(.system(size: 8)).foregroundStyle(.secondary), at: point(axis, r, offset: 0.1))
255 }
256 }
257 }
258 for axis in 0..<n {
259 var line = Path()
260 line.move(to: center)
261 line.addLine(to: point(axis, 1.1))
262 context.stroke(line, with: .color(.primary), lineWidth: 1)
263 context.draw(Text(radar.axes[axis].label), at: point(axis, 1.2))
264 }
265 for s in radar.series.indices {
266 var shape = Path()
267 for (axis, a) in radar.axes.enumerated() where s < a.values.count && a.high != a.low {
268 let p = point(axis, (a.values[s] - a.low) / (a.high - a.low))
269 if shape.isEmpty { shape.move(to: p) } else { shape.addLine(to: p) }
270 }
271 shape.closeSubpath()
272 context.fill(shape, with: .color(Radar.color(s).opacity(0.2)))
273 context.stroke(shape, with: .color(Radar.color(s)), lineWidth: 1.5)
274 }
275 }
276 .aspectRatio(1, contentMode: .fit)
277 HStack(spacing: 16) {
278 ForEach(Array(radar.series.enumerated()), id: \.offset) { s, name in
279 HStack(spacing: 4) {
280 Rectangle().fill(Radar.color(s).opacity(0.4)).frame(width: 16, height: 10)
281 Text(name).font(.caption)
282 }
283 }
284 }
285 }
286 }
287
288 /// gnuplot's colour for series `i`.
289 static func color(_ i: Int) -> Color {
290 let v = Int(TablePlot.colors[i % TablePlot.colors.count].dropFirst(), radix: 16) ?? 0
291 return Color(red: Double(v >> 16 & 255) / 255, green: Double(v >> 8 & 255) / 255, blue: Double(v & 255) / 255)
292 }
293}
294
168295/// A matrix as gnuplot's `splot … matrix with lines` draws it: a wireframe seen from its
169296/// default view, rows and columns along the floor and values up.
170297struct Wireframe: View {
@@ -227,8 +354,20 @@ public enum PlotOutput {
227354 return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: OrgPaths.home)).appendingPathComponent(expanded)
228355 }
229356
230 /// The chart as gnuplot's default 640×480, as PNG, JPEG or PDF by the file's extension.
357 /// The options a chart drawn here leaves out, for the result message.
358 public static func note(_ plot: TablePlot.Plot) -> String? {
359 let unfollowed = TablePlot.settings(plot).unfollowed
360 return unfollowed.isEmpty ? nil : "Not followed without gnuplot: " + unfollowed.joined(separator: ", ")
361 }
362
363 /// The chart as gnuplot's default 640×480, as PNG, JPEG, PDF or SVG by the file's extension.
231364 public static func write(_ plot: TablePlot.Plot, to url: URL) throws {
365 if url.pathExtension.lowercased() == "svg" {
366 let svg: String
367 do { svg = try TablePlot.svg(plot) } catch { throw Failure(description: "\(error)") }
368 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
369 return try svg.write(to: url, atomically: true, encoding: .utf8)
370 }
232371 let renderer = ImageRenderer(content: PlotChart(plot, still: true).frame(width: 640, height: 480).background(Color.white).environment(\.colorScheme, .light))
233372 renderer.scale = 2
234373 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
@@ -253,7 +392,7 @@ public enum PlotOutput {
253392 CGImageDestinationAddImage(destination, image, nil)
254393 guard CGImageDestinationFinalize(destination) else { throw Failure(description: "Can't write \(url.lastPathComponent)") }
255394 default:
256 throw Failure(description: "Without gnuplot, plots are written as .png, .jpg or .pdf, not .\(url.pathExtension)")
395 throw Failure(description: "Without gnuplot, plots are written as .png, .jpg, .pdf or .svg, not .\(url.pathExtension)")
257396 }
258397 }
259398}
Sources/OrgCore/Compute/PlotSVG.swift added +179
@@ -0,0 +1,179 @@
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 /// An axis: its ends, widened to whole steps where they're not given, and its ticks.
16 struct Axis {
17 var low: Double
18 var high: Double
19 var log: Bool
20 var ticks: [Double] = []
21
22 init(values: [Double], given: Settings.Range?, log: Bool, step: Double?, zero: Bool) {
23 var data = values.filter { !log || $0 > 0 }
24 if zero, !log { data.append(0) }
25 var low = given?.low ?? data.min() ?? 0, high = given?.high ?? data.max() ?? 1
26 if low == high { (low, high) = log ? (low / 10, high * 10) : (low - 1, high + 1) }
27 if low > high { swap(&low, &high) }
28 self.log = log
29 if log {
30 if given?.low == nil { low = pow(10, log10(low).rounded(.down)) }
31 if given?.high == nil { high = pow(10, log10(high).rounded(.up)) }
32 ticks = Array(Int(log10(low).rounded(.up))...Int(log10(high).rounded(.down))).map { pow(10, Double($0)) }
33 } else {
34 let step = step ?? TablePlot.niceStep(high - low)
35 if given?.low == nil { low = (low / step).rounded(.down) * step }
36 if given?.high == nil { high = (high / step).rounded(.up) * step }
37 var t = (low / step).rounded(.up) * step
38 while t <= high + step * 1e-9, ticks.count < 200 { ticks.append(abs(t) < step * 1e-9 ? 0 : t); t += step }
39 }
40 self.low = low
41 self.high = high
42 }
43
44 func fraction(_ v: Double) -> Double {
45 log ? (log10(v) - log10(low)) / (log10(high) - log10(low)) : (v - low) / (high - low)
46 }
47 }
48
49 static func escaped(_ s: String) -> String {
50 s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
51 .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
52 }
53
54 static func number(_ v: Double) -> String { String(format: "%.2f", v) }
55
56 public static func svg(_ plot: Plot, calendar: Calendar = .current) throws -> String {
57 guard plot.options.type == "2d" else {
58 throw Failure(description: "Without gnuplot, only 2d plots are written as .svg; use .png, .jpg or .pdf")
59 }
60 let s = settings(plot), with = plot.options.with
61 let series = series(plot, calendar: calendar)
62 let bars = ["boxes", "histograms", "hist"].contains(with)
63 var categories: [String] = []
64 for p in series.flatMap(\.points) { if case .label(let l) = p.x, !categories.contains(l) { categories.append(l) } }
65 let dates = series.contains { $0.points.contains { if case .date = $0.x { true } else { false } } }
66 func xValue(_ x: Series.X) -> Double {
67 switch x {
68 case .number(let n): n
69 case .date(let d): d.timeIntervalSince1970
70 case .label(let l): Double(categories.firstIndex(of: l)!)
71 }
72 }
73 func bound(_ key: String) -> Double? { if case .number(let n)? = plot.options[key] { n } else { nil } }
74 func given(_ set: Settings.Range?, _ low: String, _ high: String) -> Settings.Range? {
75 let r = Settings.Range(low: set?.low ?? bound(low), high: set?.high ?? bound(high))
76 return r.low == nil && r.high == nil ? nil : r
77 }
78 let ys = series.flatMap { $0.points.map(\.y) }
79 let y = Axis(values: ys, given: given(s.yrange, "ymin", "ymax"), log: s.logY, step: s.ytics, zero: bars || with == "impulses")
80 var x: Axis
81 if !categories.isEmpty {
82 x = Axis(values: [], given: .init(low: -0.5, high: Double(categories.count) - 0.5), log: false, step: 1, zero: false)
83 x.ticks = categories.indices.map(Double.init)
84 } else {
85 x = Axis(values: series.flatMap { $0.points.map { xValue($0.x) } }, given: given(s.xrange, "xmin", "xmax"), log: s.logX, step: s.xtics, zero: false)
86 }
87
88 let width = 640.0, height = 480.0
89 let left = 60.0 + (s.ylabel == nil ? 0 : 20), right = 620.0
90 let top = 20.0 + (s.title == nil ? 0 : 20), bottom = height - 40 - (s.xlabel == nil ? 0 : 20)
91 func px(_ v: Double) -> Double { left + x.fraction(v) * (right - left) }
92 func py(_ v: Double) -> Double { bottom - y.fraction(v) * (bottom - top) }
93 func xLabel(_ t: Double) -> String {
94 if !categories.isEmpty { return categories[Int(t)] }
95 if dates {
96 let c = calendar.dateComponents([.year, .month, .day], from: Date(timeIntervalSince1970: t))
97 return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)
98 }
99 return String(format: "%g", t)
100 }
101
102 var out = """
103 <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">
104 <rect width="\(Int(width))" height="\(Int(height))" fill="white"/>
105 <clipPath id="plot"><rect x="\(number(left))" y="\(number(top))" width="\(number(right - left))" height="\(number(bottom - top))"/></clipPath>
106
107 """
108 func add(_ line: String) { out += line + "\n" }
109 for t in x.ticks where t >= x.low && t <= x.high {
110 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\"/>") }
111 add("<line x1=\"\(number(px(t)))\" y1=\"\(number(bottom))\" x2=\"\(number(px(t)))\" y2=\"\(number(bottom - 6))\" stroke=\"black\"/>")
112 add("<text x=\"\(number(px(t)))\" y=\"\(number(bottom + 16))\" text-anchor=\"middle\">\(escaped(xLabel(t)))</text>")
113 }
114 for t in y.ticks where t >= y.low && t <= y.high {
115 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\"/>") }
116 add("<line x1=\"\(number(left))\" y1=\"\(number(py(t)))\" x2=\"\(number(left + 6))\" y2=\"\(number(py(t)))\" stroke=\"black\"/>")
117 add("<text x=\"\(number(left - 6))\" y=\"\(number(py(t) + 4))\" text-anchor=\"end\">\(escaped(String(format: "%g", t)))</text>")
118 }
119 add("<rect x=\"\(number(left))\" y=\"\(number(top))\" width=\"\(number(right - left))\" height=\"\(number(bottom - top))\" fill=\"none\" stroke=\"black\"/>")
120 if let title = s.title { add("<text x=\"320\" y=\"24\" text-anchor=\"middle\" font-size=\"14\">\(escaped(title))</text>") }
121 if let label = s.xlabel { add("<text x=\"\(number((left + right) / 2))\" y=\"\(number(height - 12))\" text-anchor=\"middle\">\(escaped(label))</text>") }
122 if let label = s.ylabel { add("<text transform=\"translate(16 \(number((top + bottom) / 2))) rotate(-90)\" text-anchor=\"middle\">\(escaped(label))</text>") }
123
124 add("<g clip-path=\"url(#plot)\">")
125 let xs = series.flatMap { $0.points.map { xValue($0.x) } }.sorted()
126 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))
127 let base = py(y.log ? y.low : min(max(0, y.low), y.high))
128 for (i, s) in series.enumerated() {
129 let color = colors[i % colors.count]
130 let points = s.points.filter { (!y.log || $0.y > 0) && (!x.log || xValue($0.x) > 0) }.map { (px(xValue($0.x)), py($0.y)) }
131 guard !points.isEmpty else { continue }
132 func polyline(_ p: [(Double, Double)]) {
133 add("<polyline fill=\"none\" stroke=\"\(color)\" stroke-width=\"1.5\" points=\"" + p.map { "\(number($0.0)),\(number($0.1))" }.joined(separator: " ") + "\"/>")
134 }
135 switch with {
136 case "points", "dots", "linespoints":
137 if with == "linespoints" { polyline(points) }
138 for (px, py) in points { add("<circle cx=\"\(number(px))\" cy=\"\(number(py))\" r=\"\(with == "dots" ? 1 : 3)\" fill=\"none\" stroke=\"\(color)\"/>") }
139 case "impulses":
140 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\"/>") }
141 case "boxes", "histograms", "hist":
142 let group = spacing * 0.8, bar = group / Double(series.count)
143 for (px, py) in points {
144 let x0 = px - group / 2 + bar * Double(i)
145 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)\"/>")
146 }
147 case "steps", "fsteps":
148 var stepped = [points[0]]
149 for p in points.dropFirst() {
150 stepped.append(with == "steps" ? (p.0, stepped.last!.1) : (stepped.last!.0, p.1))
151 stepped.append(p)
152 }
153 polyline(stepped)
154 default:
155 polyline(points)
156 }
157 }
158 add("</g>")
159
160 var showKey = true, vertical = "top", horizontal = "right"
161 switch s.key {
162 case .off: showKey = false
163 case .at(let v, let h): vertical = v ?? vertical; horizontal = h ?? horizontal
164 case nil: break
165 }
166 if showKey {
167 for (i, s) in series.enumerated() {
168 let color = colors[i % colors.count]
169 let row = vertical == "top" ? top + 16 + Double(i) * 16 : bottom - 10 - Double(series.count - 1 - i) * 16
170 let sample = horizontal == "right" ? right - 50 : left + 10
171 let text = horizontal == "right" ? "<text x=\"\(number(sample - 6))\" y=\"\(number(row + 4))\" text-anchor=\"end\">"
172 : "<text x=\"\(number(sample + 46))\" y=\"\(number(row + 4))\">"
173 add(text + escaped(s.label) + "</text>")
174 add("<line x1=\"\(number(sample))\" y1=\"\(number(row))\" x2=\"\(number(sample + 40))\" y2=\"\(number(row))\" stroke=\"\(color)\" stroke-width=\"\(bars ? 8 : 1.5)\"/>")
175 }
176 }
177 return out + "</svg>\n"
178 }
179}
Sources/OrgCore/Compute/PlotSettings.swift added +112
@@ -0,0 +1,112 @@
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
17 public var title: String?
18 public var xlabel: String?
19 public var ylabel: String?
20 public var xrange: Range?
21 public var yrange: Range?
22 public var logX = false
23 public var logY = false
24 public var grid = false
25 public var key: Key?
26 public var xtics: Double?
27 public var ytics: Double?
28 /// The options not followed, as written in `#+PLOT`: `set:"…"`, `line:"…"`, `script:"…"`.
29 public var unfollowed: [String] = []
30 }
31
32 /// The `set` commands each kind of chart can follow.
33 static func followed(_ plot: Plot) -> Set<String> {
34 switch plot.options.type {
35 case "2d":
36 let numericX = plot.options.ind <= 0 || !(plot.timeInd || plot.textInd || plot.options.with == "histograms")
37 return numericX ? ["title", "xlabel", "ylabel", "xrange", "yrange", "logscale", "grid", "key", "xtics", "ytics"]
38 : ["title", "xlabel", "ylabel", "yrange", "logscale y", "grid", "key", "ytics"]
39 case "grid": return ["title", "xlabel", "ylabel", "key"]
40 case "3d" where plot.options["map"]?.truthy == true: return ["title", "xlabel", "ylabel", "key"]
41 // The radar script sets its own key, after these.
42 default: return ["title"]
43 }
44 }
45
46 /// The script's `title:`, `line:` and `set:` in the order gnuplot reads them, so a later
47 /// one wins.
48 public static func settings(_ plot: Plot) -> Settings {
49 var s = Settings()
50 let o = plot.options
51 let follows = followed(plot)
52 s.title = o.title
53 var lines: [String] = [], sets: [String] = []
54 for line in o.lines {
55 if !(line.hasPrefix("set ") && apply(String(line.dropFirst(4)), to: &s, follows: follows)) { lines.append("line:\"\(line)\"") }
56 }
57 for set in o.sets where !apply(set, to: &s, follows: follows) { sets.append("set:\"\(set)\"") }
58 // Each comes twice, as Org reads the options twice; list them once, as written.
59 for u in lines.reversed() + sets.reversed() where !s.unfollowed.contains(u) { s.unfollowed.append(u) }
60 if let script = o["script"] { s.unfollowed.append("script:\"\(script)\"") }
61 return s
62 }
63
64 static func apply(_ command: String, to s: inout Settings, follows: Set<String>) -> Bool {
65 let words = command.split(separator: " ", maxSplits: 1).map(String.init)
66 guard let name = words.first else { return false }
67 let rest = words.count > 1 ? words[1].trimmingCharacters(in: .whitespaces) : ""
68 func quoted() -> String? {
69 guard let m = rest.firstMatch(of: /^(["'])(.*)\1$/) else { return nil }
70 return String(m.2)
71 }
72 func range() -> Settings.Range? {
73 guard let m = rest.firstMatch(of: /^\[\s*([^:\]]*?)\s*:\s*([^:\]]*?)\s*\]$/) else { return nil }
74 func bound(_ t: Substring) -> Double?? { t.isEmpty || t == "*" ? .some(nil) : Double(t).map { .some($0) } }
75 guard let low = bound(m.1), let high = bound(m.2) else { return nil }
76 return Settings.Range(low: low, high: high)
77 }
78 func step() -> Double? { Double(rest).flatMap { $0 > 0 ? $0 : nil } }
79 switch name {
80 case "title", "xlabel", "ylabel":
81 guard follows.contains(name), let text = quoted() else { return false }
82 if name == "title" { s.title = text } else if name == "xlabel" { s.xlabel = text } else { s.ylabel = text }
83 case "xrange", "yrange":
84 guard follows.contains(name), let r = range() else { return false }
85 if name == "xrange" { s.xrange = r } else { s.yrange = r }
86 case "logscale":
87 let axes = rest.isEmpty ? "xy" : rest
88 guard ["x", "y", "xy", "yx"].contains(axes), follows.contains("logscale") || (axes == "y" && follows.contains("logscale y")) else { return false }
89 if axes.contains("x") { s.logX = true }
90 if axes.contains("y") { s.logY = true }
91 case "grid":
92 guard follows.contains(name), rest.isEmpty else { return false }
93 s.grid = true
94 case "key":
95 let words = rest.split(separator: " ").map(String.init)
96 guard follows.contains(name), words.allSatisfy(["off", "top", "bottom", "left", "right"].contains) else { return false }
97 if words == ["off"] {
98 s.key = .off
99 } else {
100 let vertical = words.filter { $0 == "top" || $0 == "bottom" }, horizontal = words.filter { $0 == "left" || $0 == "right" }
101 guard !words.contains("off"), vertical.count <= 1, horizontal.count <= 1 else { return false }
102 s.key = .at(vertical: vertical.first, horizontal: horizontal.first)
103 }
104 case "xtics", "ytics":
105 guard follows.contains(name), let step = step() else { return false }
106 if name == "xtics" { s.xtics = step } else { s.ytics = step }
107 default:
108 return false
109 }
110 return true
111 }
112}
Sources/OrgCore/Compute/TablePlot.swift +7 −3
@@ -132,8 +132,8 @@ public enum TablePlot {
132132 }
133133 let first = table.first.flatMap { $0 } ?? (table.count > 1 ? table[1] : nil)
134134 let columns = first?.count ?? 0
135 guard ["2d", "3d", "grid"].contains(options.type) else {
136 throw Failure(description: options.type == "radar" ? "Radar plots need gnuplot" : "Org-plot type `\(options.type)' is undefined")
135 guard ["2d", "3d", "grid", "radar"].contains(options.type) else {
136 throw Failure(description: "Org-plot type `\(options.type)' is undefined")
137137 }
138138 if table.count > 1, table[1] == nil, let header = table[0] {
139139 options.values["labels"] = .list(header.map { .string($0) })
@@ -152,6 +152,7 @@ public enum TablePlot {
152152 }
153153 }
154154 }
155 if options.type == "radar", options["script"] == nil { _ = try radar(plot) }
155156 return plot
156157 }
157158
@@ -243,7 +244,8 @@ public enum TablePlot {
243244 /// `org-plot/gnuplot-script`, with `org-plot/gnuplot-term-extra` and the preamble empty.
244245 /// `output` is where `file:` goes, expanded. A `preface` leaves out the plot command, for
245246 /// a `script:` file to follow.
246 public static func script(_ plot: Plot, dataFile: String, output: String?, yLabels: [(Int, String)] = [], preface: Bool = false) -> String {
247 /// `setupFile` is where a radar plot's `radarSetup` goes.
248 public static func script(_ plot: Plot, dataFile: String, output: String?, yLabels: [(Int, String)] = [], preface: Bool = false, setupFile: String = "") -> String {
247249 let o = plot.options
248250 var script = "reset"
249251 func add(_ line: String?) { if let line { script += "\n" + line } }
@@ -281,6 +283,8 @@ public enum TablePlot {
281283 add("plot " + plotLines.joined(separator: ",\\\n "))
282284 case "3d":
283285 add("splot '\(dataFile)' matrix with \(with) title ''")
286 case "radar":
287 if let radar = try? radar(plot) { add(radarScript(radar, setupFile: setupFile)) }
284288 default:
285289 add("splot '\(dataFile)' with \(with) title ''")
286290 }
Sources/OrgCore/Compute/TablePlotRadar.swift added +228
@@ -0,0 +1,228 @@
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]+)?/) else { return (0, true) }
30 let text = String(m.0)
31 return (Double(text) ?? 0, text.firstMatch(of: /\.[0-9]|[eE]/) == nil)
32 }
33
34 static func printed(_ n: (value: Double, integer: Bool)) -> String {
35 n.integer ? String(Int(n.value)) : Elisp.floatText(n.value)
36 }
37
38 /// `org--plot/values-stats`.
39 static func stats(_ nums: [(value: Double, integer: Bool)], hardMin: Double? = nil, hardMax: Double? = nil)
40 -> (factor: Double, niceMin: (value: Double, integer: Bool), niceMax: (value: Double, integer: Bool)) {
41 let low = hardMin ?? nums.map(\.value).min()!, high = hardMax ?? nums.map(\.value).max()!
42 let range = high - low
43 guard range != 0 else { return (1, nums[0], nums[0]) }
44 let order = (1 - log10(range)).rounded(.up)
45 let factor = pow(10, order)
46 return (factor, ((low * factor).rounded(.down) / factor, false), ((high * factor).rounded(.up) / factor, false))
47 }
48
49 /// `org--plot/sensible-tick-num`, or nil where Emacs signals an error or never returns.
50 static func sensibleTicks(_ rows: [[String]], hardMin: Double?, hardMax: Double?) -> Int? {
51 var decompositions: [[(Int, Double)]] = []
52 for row in rows {
53 let s = stats(row.dropFirst().map(lispNumber), hardMin: hardMin, hardMax: hardMax)
54 var value = Int((s.factor * (s.niceMax.value - s.niceMin.value)).rounded(.toNearestOrEven))
55 if value % 10 == 0 { value /= 10 }
56 // `org--plot/prime-factors` loops forever on 0.
57 guard value > 0 else { return nil }
58 var factors: [Int] = [], i = 1
59 while value != 1 {
60 i += 1
61 if value % i == 0 { factors.insert(i, at: 0); value /= i; i -= 1 }
62 }
63 // `org--plot/item-frequencies`, keys in `seq-group-by`'s order.
64 var groups: [(Int, Int)] = []
65 for f in factors.reversed() {
66 if let at = groups.firstIndex(where: { $0.0 == f }) { groups[at].1 += 1 } else { groups.insert((f, 1), at: 0) }
67 }
68 decompositions.append(groups.map { ($0.0, Double($0.1) / Double(factors.count)) })
69 }
70 // `org--plot/merge-alists` needs two lists.
71 func merge(_ lists: ArraySlice<[(Int, Double)]>) -> [(Int, Double)] {
72 let a1 = lists.first!
73 let a2 = lists.count > 2 ? merge(lists.dropFirst()) : lists[lists.startIndex + 1]
74 // `cl-union` with :test: the longer list, the shorter's new keys pushed on its front.
75 var (keys, other) = (a1.map(\.0), a2.map(\.0))
76 if !keys.isEmpty, !other.isEmpty {
77 if keys.count < other.count { swap(&keys, &other) }
78 for k in other where !keys.contains(k) { keys.insert(k, at: 0) }
79 } else if keys.isEmpty {
80 keys = other
81 }
82 func lookup(_ k: Int, _ list: [(Int, Double)]) -> Double { list.first { $0.0 == k }?.1 ?? 0 }
83 return keys.map { ($0, lookup($0, a1) + lookup($0, a2)) }
84 }
85 guard decompositions.count >= 2 else { return nil }
86 let weighted = merge(decompositions[...]).enumerated().sorted { $0.element.1 != $1.element.1 ? $0.element.1 > $1.element.1 : $0.offset < $1.offset }.map(\.element)
87 // `org--plot/nice-frequency-pick`.
88 var pick: [Int]
89 switch weighted.count {
90 case 0: return nil
91 case 1: pick = [weighted[0].0]
92 case 2: pick = 3 <= weighted[0].1 / weighted[1].1 ? [weighted[0].0, weighted[0].0] : [weighted[0].0, weighted[1].0]
93 default:
94 let total = weighted.map(\.1).reduce(0, +)
95 let n = weighted.map { ($0.0, $0.1 / total) }
96 pick = [n[0].0]
97 let r12 = n[0].1 / n[1].1, r23 = n[1].1 / n[2].1, r13 = r12 * r23
98 if r12 > 4 { pick.insert(n[0].0, at: 0) }
99 if r12 < Double(n[1].0), pick.reduce(1, *) * n[1].0 < 30 { pick.insert(n[1].0, at: 0) }
100 if r13 < Double(n[2].0), pick.reduce(1, *) * n[2].0 < 30 { pick.insert(n[2].0, at: 0) }
101 }
102 return pick.reduce(1, *)
103 }
104
105 /// The radar plot's axes, series and ticks, as `org--plot/radar` works them out.
106 public static func radar(_ plot: Plot) throws -> Radar {
107 let rows = plot.rows.compactMap { $0 }
108 guard !rows.isEmpty, rows.allSatisfy({ $0.count > 1 }) else {
109 throw Failure(description: "A radar plot needs a name and a value in each row")
110 }
111 func number(_ key: String) throws -> Double? {
112 guard let v = plot.options[key] else { return nil }
113 guard case .number(let n) = v else { throw Failure(description: "\(key): must be a number") }
114 return n
115 }
116 let ymin = try number("ymin"), ymax = try number("ymax")
117 let ticks: Int
118 if let given = try number("ticks") {
119 ticks = Int(given)
120 } else if let sensible = sensibleTicks(rows, hardMin: ymin, hardMax: ymax) {
121 ticks = sensible
122 } else {
123 throw Failure(description: "Org can't choose this radar plot's ticks; give ticks:")
124 }
125 let axes = rows.map { row -> Radar.Axis in
126 let nums = row.dropFirst().map(lispNumber)
127 let s = stats(nums)
128 return Radar.Axis(label: row[0], fields: Array(row.dropFirst()), values: nums.map(\.value),
129 low: ymin ?? s.niceMin.value, high: ymax ?? s.niceMax.value,
130 lowText: plot.options["ymin"]?.description ?? printed(s.niceMin),
131 highText: plot.options["ymax"]?.description ?? printed(s.niceMax))
132 }
133 return Radar(axes: axes, series: Array((plot.options.labels ?? []).dropFirst()), ticks: ticks, sharedTicks: ymin != nil && ymax != nil)
134 }
135
136 /// The setup file `org--plot/radar` writes: the data and each axis's scale.
137 public static func radarSetup(_ plot: Plot) throws -> String {
138 let radar = try radar(plot)
139 let axes = radar.axes + radar.axes.prefix(1)
140 let data = "\"" + (plot.options.labels ?? []).joined(separator: "\" \"") + "\"\n"
141 + axes.map { "\"\($0.label)\" " + $0.fields.joined(separator: " ") }.joined(separator: "\n")
142 let settings = axes.map { "\"\($0.label)\" \($0.lowText) \($0.highText) \(radar.ticks == 0 ? 2 : radar.ticks)" }.joined(separator: "\n")
143 return "# Data\n$Data <<HEREHAVESOMEDATA\n\(data)\nHEREHAVESOMEDATA\nHeaderLines = 1\n\n"
144 + "# Settings for scale and offset adjustments\n# axis min max tics axisLabelXoff axisLabelYoff\n$Settings <<EOD\n\(settings)\nEOD\n"
145 }
146
147 /// `org--plot/radar-template` filled in.
148 static func radarScript(_ radar: Radar, setupFile: String) -> String {
149 let axis = radar.sharedTicks ? "1" : "$1"
150 let ticks = radar.ticks == 0 ? "" : """
151 '++' u (PosX($1,$2/TicCount)):(PosY($1,$2/TicCount)): \\
152 \t(PosX($1+1,$2/TicCount)-PosX($1,$2/TicCount)): \\
153 \t(PosY($1+1,$2/TicCount)-PosY($1,$2/TicCount)) w vec as 2 not, \\
154 '++' u (TicLabelPosX(\(axis),$2)):(TicLabelPosY(\(axis),$2)): \\
155 \t(sprintf('%g',TicValue(\(axis),$2))) w labels font ',8' @fgat not
156 """
157 return """
158 ### spider plot/chart with gnuplot
159 # also known as: radar chart, web chart, star chart, cobweb chart,
160 # radar plot, web plot, star plot, cobweb plot, etc. ...
161 set datafile separator ' '
162 set size square
163 unset tics
164 set angles degree
165 set key bmargin center horizontal
166 unset border
167
168 # Load data and setup
169 load "\(setupFile)"
170
171 # General settings
172 DataColCount = words($Data[1])-1
173 AxesCount = |$Data|-HeaderLines-1
174 AngleOffset = 90
175 Max = 1
176 d=0.1*Max
177 Direction = -1 # counterclockwise=1, clockwise = -1
178
179 # Tic settings
180 TicCount = \(radar.ticks == 0 ? 2 : radar.ticks)
181 TicOffset = 0.1
182 TicValue(axis,i) = real(i)*(word($Settings[axis],3)-word($Settings[axis],2)) \\
183 \t / word($Settings[axis],4)+word($Settings[axis],2)
184 TicLabelPosX(axis,i) = PosX(axis,i/TicCount) + PosY(axis, TicOffset)
185 TicLabelPosY(axis,i) = PosY(axis,i/TicCount) - PosX(axis, TicOffset)
186 TicLen = 0.03
187 TicdX(axis,i) = 0.5*TicLen*cos(alpha(axis)-90)
188 TicdY(axis,i) = 0.5*TicLen*sin(alpha(axis)-90)
189
190 # Label
191 LabOffset = 0.10
192 LabX(axis) = PosX(axis+1,Max+2*d) + PosY(axis, LabOffset)
193 LabY(axis) = PosY($0+1,Max+2*d)
194
195 # Functions
196 alpha(axis) = (axis-1)*Direction*360.0/AxesCount+AngleOffset
197 PosX(axis,R) = R*cos(alpha(axis))
198 PosY(axis,R) = R*sin(alpha(axis))
199 Scale(axis,value) = real(value-word($Settings[axis],2))/(word($Settings[axis],3)-word($Settings[axis],2))
200
201 # Spider settings
202 set style arrow 1 dt 1 lw 1.0 @fgal head filled size 0.06,25 # style for axes
203 set style arrow 2 dt 2 lw 0.5 @fgal nohead # style for weblines
204 set style arrow 3 dt 1 lw 1 @fgal nohead # style for axis tics
205 set samples AxesCount
206 set isosamples TicCount
207 set urange[1:AxesCount]
208 set vrange[1:TicCount]
209 set style fill transparent solid 0.2
210
211 set xrange[-Max-4*d:Max+4*d]
212 set yrange[-Max-4*d:Max+4*d]
213 plot \\
214 '+' u (0):(0):(PosX($0,Max+d)):(PosY($0,Max+d)) w vec as 1 not, \\
215 $Data u (LabX($0)): \\
216 \t(LabY($0)):1 every ::HeaderLines w labels center enhanced @fgt not, \\
217 for [i=1:DataColCount] $Data u (PosX($0+1,Scale($0+1,column(i+1)))): \\
218 \t(PosY($0+1,Scale($0+1,column(i+1)))) every ::HeaderLines w filledcurves lt i title word($Data[1],i+1), \\
219 \(ticks)
220 # '++' u (PosX($1,$2/TicCount)-TicdX($1,$2/TicCount)): \\
221 # (PosY($1,$2/TicCount)-TicdY($1,$2/TicCount)): \\
222 # (2*TicdX($1,$2/TicCount)):(2*TicdY($1,$2/TicCount)) \\
223 # w vec as 3 not, \\
224 ### end of code
225
226 """
227 }
228}
Sources/OrgPrograms/Gnuplot.swift +3 −1
@@ -22,7 +22,9 @@ extension PlotOutput {
2222 if plot.options.file == nil { plot.options.values["file"] = .string(output.path) }
2323 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot), [])
2424 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)
2628 if let custom = plot.options["script"]?.description {
2729 let path = OrgPaths.expandingTilde(custom)
2830 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path)
Sources/Orgstar/ContentView.swift +4 −3
@@ -970,18 +970,19 @@ struct ContentView: View {
970970 guard reach([url.path]) else { return }
971971 do {
972972 try PlotOutput.write(plot, to: url)
973 plotWritten(url, editor: editor)
973 plotWritten(url, editor: editor, note: PlotOutput.note(plot))
974974 } catch {
975975 commands.show("\(error)")
976976 }
977977 } else {
978978 panel = .plot(UUID(), plot)
979 if let note = PlotOutput.note(plot) { commands.show(note) }
979980 }
980981 }
981982
982983 /// The image is where `file:` says; a link to it shows it again.
983 private func plotWritten(_ url: URL, editor: OrgEditor) {
984 commands.show("Plot written to \(url.lastPathComponent)")
984 private func plotWritten(_ url: URL, editor: OrgEditor, note: String? = nil) {
985 commands.show("Plot written to \(url.lastPathComponent)" + (note.map { ". " + $0 } ?? ""))
985986 if editor.showsImages { editor.refreshImages() }
986987 }
987988
Sources/OrgstarMobile/EditorScreen.swift +2 −1
@@ -614,10 +614,11 @@ extension EditorScreen {
614614 let plot = try TablePlot.plot(context.text, at: context.caret)
615615 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
616616 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 } ?? "")
618618 if editor.showsImages { editor.restyleAll() }
619619 } else {
620620 sheet = .plot(plot)
621 if let note = PlotOutput.note(plot) { message = note }
621622 }
622623 } catch {
623624 message = "\(error)"
Tests/OrgAppTests/PlotChartTests.swift +73 −1
@@ -13,6 +13,9 @@ struct PlotChartTests {
1313 "#+PLOT: ind:1 with:histograms file:\"b.jpg\"\n| name | n |\n|------+---|\n| a | 3 |\n| b | 5 |\n",
1414 "#+PLOT: type:grid ind:1 file:\"c.pdf\"\n| r | a | b |\n|---+---+---|\n| x | 1 | 2 |\n| y | 3 | 4 |\n",
1515 "#+PLOT: type:3d file:\"d.png\"\n| 1 | 2 | 3 |\n| 2 | 4 | 6 |\n| 3 | 6 | 9 |\n",
16 "#+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",
17 "#+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",
18 "#+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",
1619 ]
1720 for text in texts {
1821 let plot = try TablePlot.plot(text, at: (text as NSString).range(of: "|").location)
@@ -26,7 +29,76 @@ struct PlotChartTests {
2629 }
2730 }
2831 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)!) }
32 try PlotOutput.write(svg, to: PlotOutput.file(svg, directory: folder)!)
33 #expect(try String(contentsOf: folder.appendingPathComponent("e.svg"), encoding: .utf8).hasPrefix("<svg"))
34 let grid = try TablePlot.plot("#+PLOT: type:grid file:\"f.svg\"\n| 1 | 2 |\n| 3 | 4 |\n", at: 35)
35 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(grid, to: PlotOutput.file(grid, directory: folder)!) }
36 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(grid, to: folder.appendingPathComponent("g.eps")) }
37 }
38
39 static func plot(_ text: String) throws -> TablePlot.Plot {
40 try TablePlot.plot(text, at: (text as NSString).range(of: "\n|").location + 1)
41 }
42
43 static let table = "| x | a | b |\n|---+---+---|\n| 1 | 2 | 30 |\n| 2 | 4 | 10 |\n| 3 | 3 | 50 |\n"
44
45 @Test func followsTheSetSubset() throws {
46 let sets = ["title 'Set'", "xlabel 'Day'", "ylabel 'Count'", "xrange [0:10]", "yrange [*:60]", "logscale y",
47 "grid", "key left top", "xtics 2", "ytics 0.5"]
48 let plot = try Self.plot("#+PLOT: title:\"Given\" ind:1 " + sets.map { "set:\"\($0)\"" }.joined(separator: " ") + "\n" + Self.table)
49 let s = TablePlot.settings(plot)
50 #expect(s.title == "Set" && s.xlabel == "Day" && s.ylabel == "Count")
51 #expect(s.xrange?.low == 0 && s.xrange?.high == 10 && s.yrange?.low == nil && s.yrange?.high == 60)
52 #expect(s.logY && !s.logX && s.grid && s.xtics == 2 && s.ytics == 0.5)
53 #expect(s.key == .at(vertical: "top", horizontal: "left"))
54 #expect(s.unfollowed.isEmpty && PlotOutput.note(plot) == nil)
55
56 #expect(TablePlot.settings(try Self.plot("#+PLOT: set:\"logscale\"\n" + Self.table)).logX)
57 #expect(TablePlot.settings(try Self.plot("#+PLOT: set:\"key off\"\n" + Self.table)).key == .off)
58 #expect(TablePlot.settings(try Self.plot("#+PLOT: line:\"set key bottom\"\n" + Self.table)).key == .at(vertical: "bottom", horizontal: nil))
59 // gnuplot reads title:, then line:, then set:, so a set: wins.
60 #expect(TablePlot.settings(try Self.plot("#+PLOT: line:\"set title 'L'\" set:\"title 'S'\"\n" + Self.table)).title == "S")
61 }
62
63 @Test func reportsWhatItDoesntFollow() throws {
64 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)
65 #expect(TablePlot.settings(plot).unfollowed == ["line:\"plot sin(x)\"", "set:\"style fill solid\"", "set:\"xrange [a:b]\"", "script:\"plot.gp\""])
66 #expect(PlotOutput.note(plot) == "Not followed without gnuplot: line:\"plot sin(x)\", set:\"style fill solid\", set:\"xrange [a:b]\", script:\"plot.gp\"")
67 // Text on the x axis has no range or steps; a heat map has no log scale; a radar plot sets its own key.
68 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")
69 #expect(TablePlot.settings(text).unfollowed == ["set:\"xtics 2\""])
70 let grid = try Self.plot("#+PLOT: type:grid set:\"logscale\" set:\"xlabel 'C'\"\n| 1 | 2 |\n| 3 | 4 |\n")
71 #expect(TablePlot.settings(grid).unfollowed == ["set:\"logscale\""] && TablePlot.settings(grid).xlabel == "C")
72 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")
73 #expect(TablePlot.settings(radar).unfollowed == ["set:\"key off\""] && TablePlot.settings(radar).title == "R")
74 }
75
76 @Test func drawsRadarPlots() throws {
77 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-radar-\(UUID().uuidString)")
78 defer { try? FileManager.default.removeItem(at: folder) }
79 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")
80 for name in ["radar.png", "radar.pdf"] {
81 try PlotOutput.write(plot, to: folder.appendingPathComponent(name))
82 let size = (try FileManager.default.attributesOfItem(atPath: folder.appendingPathComponent(name).path)[.size] as? Int) ?? 0
83 #expect(size > 1000, "\(name) is \(size) bytes")
84 }
85 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(plot, to: folder.appendingPathComponent("radar.svg")) }
86 }
87
88 @Test func writesSVG() throws {
89 let lines = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"title 'T&C'\" set:\"xlabel 'Day'\" set:\"grid\"\n" + Self.table))
90 #expect(lines.hasPrefix("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"480\""))
91 #expect(lines.components(separatedBy: "<polyline").count - 1 == 2)
92 #expect(lines.contains(">T&amp;C</text>") && lines.contains(">Day</text>") && lines.contains("stroke-dasharray"))
93 #expect(lines.contains(">a</text>") && lines.contains(">b</text>"))
94 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"))
95 #expect(bars.components(separatedBy: "<rect x=").count - 1 == 2 + 2)
96 #expect(bars.contains(">a</text>") && !bars.contains(">v</text>") && !bars.contains("stroke-dasharray"))
97 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"))
98 #expect(log.contains(">1</text>") && log.contains(">1000</text>") && log.components(separatedBy: "<circle").count - 1 == 2)
99 let ranged = try TablePlot.svg(Self.plot("#+PLOT: ind:1 set:\"xrange [0:10]\" set:\"ytics 25\"\n" + Self.table))
100 #expect(ranged.contains(">10</text>") && ranged.contains(">25</text>") && ranged.contains(">50</text>"))
101 #expect(throws: TablePlot.Failure.self) { try TablePlot.svg(Self.plot("#+PLOT: type:3d\n| 1 | 2 |\n| 3 | 4 |\n")) }
30102 }
31103
32104 @Test func interpolatesTheMatrix() {
Tests/OrgCoreTests/TablePlotTests.swift +89 −6
@@ -57,6 +57,49 @@ struct TablePlotTests {
5757 | 1 | 2 |
5858 | 3 | 4 |
5959 """,
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 """,
60103 ]
61104
62105 static func lisp(_ s: String) -> String {
@@ -64,7 +107,7 @@ struct TablePlotTests {
64107 }
65108
66109 /// 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) {
68111 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)")
69112 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
70113 defer { try? FileManager.default.removeItem(at: folder) }
@@ -77,7 +120,8 @@ struct TablePlotTests {
77120 (provide 'gnuplot)
78121 (let ((captured nil))
79122 (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)))))
81125 (with-temp-buffer
82126 (insert \(lisp(text)))
83127 (org-mode)
@@ -88,25 +132,56 @@ struct TablePlotTests {
88132 """
89133 let log = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
90134 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)) ?? "")
92136 }
93137
94138 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: cases.indices)
95139 func scriptsAndDataMatchEmacs(index: Int) throws {
96140 let text = Self.cases[index]
97141 let dataFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-data-\(UUID().uuidString)").path
98 defer { try? FileManager.default.removeItem(atPath: dataFile) }
99 let expected = try Self.emacs(text, data: dataFile)
142 let setupFile = dataFile + "-setup"
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)
100145 let offset = (text as NSString).range(of: "|").location
101146 let plot = try TablePlot.plot(text, at: offset)
102147 var utc = Calendar(identifier: .gregorian)
103148 utc.timeZone = TimeZone(identifier: "UTC")!
104149 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 }
106155 #expect(script == expected.script, "case \(index)\nours:\n\(script)\nemacs:\n\(expected.script)")
107156 #expect(data == expected.data, "case \(index)\nours:\n\(data.debugDescription)\nemacs:\n\(expected.data.debugDescription)")
108157 }
109158
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 }
184
110185 @Test func seriesAndMatrices() throws {
111186 let plot = try TablePlot.plot(Self.cases[0], at: 100)
112187 let series = TablePlot.series(plot)
@@ -121,6 +196,14 @@ struct TablePlotTests {
121196 let m = TablePlot.matrix(grid)
122197 #expect(m.values == [[1, 2], [3, 4]] && m.rowLabels == ["r1", "r2"])
123198 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| 1 |\n", at: 0) }
199 // Emacs never returns choosing ticks for an axis whose values are all the same.
200 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| a | 1 | 1 |\n| b | 2 | 3 |\n", at: 0) }
201 // Emacs signals an error where the ranges leave nothing to pick ticks from.
202 #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) }
203 _ = try TablePlot.plot("#+PLOT: type:radar ticks:3\n| a | 1 | 1 |\n| b | 2 | 3 |\n", at: 0)
204 let radar = try TablePlot.radar(TablePlot.plot(Self.cases[9], at: 40))
205 #expect(radar.series == ["a", "b"] && radar.axes.map(\.label) == ["x", "y", "z"] && radar.sharedTicks)
206 #expect(radar.axes[2].values == [8, 3] && radar.axes[0].low == 0 && radar.axes[0].high == 8)
124207 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("no table\n", at: 0) }
125208 }
126209}
docs/manual/guide/10-tables.org +30 −8
@@ -773,7 +773,7 @@ after it, as the =#+PLOT:= lines above it say:
773773
774774| Option | Meaning |
775775|------------+-----------------------------------------------------------------------------|
776| =type= | =2d= (the default), =3d= or =grid= |
776| =type= | =2d= (the default), =3d=, =grid= or =radar= |
777777| =ind= | The column of x values, counting from 1; 0 (the default) plots against row numbers |
778778| =deps= | The columns to plot, as a list such as =(2 3)=; all but =ind= by default |
779779| =with= | =lines= (the default), =points=, =linespoints=, =impulses=, =boxes=, =histograms=, =steps=, =fsteps= |
@@ -782,7 +782,7 @@ after it, as the =#+PLOT:= lines above it say:
782782| =labels= | Names for the columns, as a list; a header row above a rule names them otherwise |
783783| =map= | With =t=, a =3d= plot is seen from above |
784784| =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 |
786786| =transpose= | With =yes=, rows become columns |
787787| =set=, =line=, =script=, =timefmt= | gnuplot commands, a line of gnuplot, a gnuplot script file and the time format, for gnuplot |
788788
@@ -791,19 +791,41 @@ a longer word (=timeind:t= sets =ind=), an unquoted value ends at a =.=, =,= or
791791options before the last =line:= are dropped, and each =set:= and =line:= that's kept comes
792792twice, as Org reads the options twice. An ind column of timestamps is plotted as dates, and one of text as labels.
793793
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 to
796highest value, or from =ymin= to =ymax=. Org works out the number of rings from the values;
797where Org can't (it signals an error, or never finishes, as for a row whose values are all
798the same), orgstar reports it and asks for =ticks:=.
799
794800On the Mac, when gnuplot is installed (orgstar looks on the same =PATH= as code blocks), the
795801table goes to gnuplot as Emacs sends it: the same data file and script, so every option and
796802gnuplot's own terminals and styles apply. A plot without =file:= is drawn to an image and shown
797803in a sheet. Without gnuplot, and on iOS, orgstar draws the plot itself with Swift Charts: =2d=
798804as 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
800gnuplot-only options are ignored. If inline images are showing, a link to the file shows the
801new plot.
802
803=type:radar= needs gnuplot; orgstar reports it.
805file), =radar= as a web. =file:= then takes =.png=, =.jpg= or =.pdf=, 640 by 480 points as
806gnuplot's default, or =.svg= for a =2d= plot. If inline images are showing, a link to the file
807shows the new plot.
808
809Without gnuplot these =set:= commands are followed, also as a =line:= that starts with =set=:
810
811| Command | Effect |
812|------------------------------------------+------------------------------------------------------------|
813| =title 'T'= | The title, over =title:= |
814| =xlabel 'X'=, =ylabel 'Y'= | The axes' names |
815| =xrange [0:10]=, =yrange [*:5]= | The axes' ranges; =*= or nothing leaves an end to the data |
816| =logscale=, =logscale x=, =logscale y= | Logarithmic axes |
817| =grid= | Grid lines at the marks |
818| =key off=, =key top left= | Hides or places the legend (top, bottom, left, right) |
819| =xtics 2=, =ytics 0.5= | A mark every so many units |
820
821=2d= plots follow all of them, except that an x axis of text or dates takes no range, steps or
822log scale. =grid= and =3d map:t= plots follow the title, axis names and key; other =3d= plots
823and =radar= plots only the title. Other commands, other =line:= options and =script:= are left
824out, and the message after plotting names them, such as =Not followed without gnuplot:
825set:"style fill solid"=.
804826
805827The [[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.
828the plot itself in the same way.
807829
808830* On iOS
809831
docs/manual/install.org +1 −1
@@ -58,7 +58,7 @@ App Store version.
5858| Sessions, graphics | JavaScript sessions; no graphics | Yes |
5959| Tangling | Yes | Yes |
6060| 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 |
6262| Export | HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX, ASCII; publishing | Also PDF through LaTeX, in Emacs |
6363| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= |
6464| Files outside your folders | After you grant access to their folder | Directly |