|
| 1 | +import strutils |
| 2 | +import sequtils |
| 3 | +import strformat |
| 4 | +import tempfile |
| 5 | +import os |
| 6 | + |
| 7 | +type Plot = ref object of RootObj |
| 8 | +method render(this: Plot): string {.base.} = "" |
| 9 | + |
| 10 | +type |
| 11 | + Figure = ref object of RootObj |
| 12 | + python*: string |
| 13 | + script*: seq[string] |
| 14 | + latex*: bool |
| 15 | + plots*: seq[Plot] |
| 16 | + |
| 17 | +proc save*(figure: Figure, dest: string) = |
| 18 | + var script = newSeq[string]() |
| 19 | + script.add "import matplotlib" |
| 20 | + script.add "matplotlib.use('Agg')" |
| 21 | + script.add "from matplotlib import rc" |
| 22 | + script.add "import matplotlib.pyplot as plt" |
| 23 | + script.add "from matplotlib.lines import Line2D" |
| 24 | + # script.add "rc('font', **{'family': '#{@font.family}', 'serif': '#{@font.styles.to_s}'})" |
| 25 | + let latex_str = if figure.latex: "True" else: "False" |
| 26 | + script.add fmt"rc('text', usetex={latex_str})" |
| 27 | + script.add "matplotlib.rcParams['text.latex.unicode']=True" |
| 28 | + for p in figure.plots: |
| 29 | + script.add p.render |
| 30 | + script.add fmt"plt.savefig('{dest}', format='png', transparent=False)" |
| 31 | + let script_str = script.join("\n") |
| 32 | + # get the temporary file |
| 33 | + var (file, name) = mkstemp(suffix = ".py") |
| 34 | + writeFile(name, script_str) |
| 35 | + echo name |
| 36 | + discard execShellCmd fmt"/usr/local/bin/python3 {name}" |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +proc newFigure*(): Figure = |
| 41 | + Figure(python: "/usr/local/bin/python3", script: newSeq[string](), latex: false) |
| 42 | + |
| 43 | +proc add*(figure: Figure, plot: Plot) = |
| 44 | + figure.plots.add plot |
| 45 | + |
| 46 | +type LinePlot[A, B] = ref object of Plot |
| 47 | + linestyle*: string |
| 48 | + x*: seq[A] |
| 49 | + y*: seq[B] |
| 50 | +method render[A,B](this: LinePlot[A,B]): string = |
| 51 | + let xs = this.x.map(proc(k:A):string = $k).join(",") |
| 52 | + let ys = this.y.map(proc(k:B):string = $k).join(",") |
| 53 | + return fmt"plt.plot([{xs}],[{ys}])" |
| 54 | + |
| 55 | +proc newLinePlot*[A,B](x: seq[A], y: seq[B]): LinePlot[A, B] = |
| 56 | + LinePlot[A, B](linestyle: "-", x: x, y: y) |
0 commit comments