Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Gnuplot in Swift

I'm trying to call gunplot from swift to produce some plots in .png. However, the program below does not work --- the resulting 1.png file is empty. If I leave the "set term aqua" though, it does call the aqua window with the plot in it. However when I try to set output to file (png or pdf) the result is always an empty file.

The gnuplot commands are ok --- I can correctly run them manually.

import Foundation

let task = NSTask()
task.launchPath = "/opt/local/bin/gnuplot"
task.currentDirectoryPath = "~"

let pipeIn = NSPipe()
task.standardInput = pipeIn
task.launch()

let plotCommand: NSString =
  "set term png\n" +
  "set output \"1.png\"\n"
  "plot sin(x)\n" +
  "q\n"

pipeIn.fileHandleForWriting.writeData(plotCommand.dataUsingEncoding(NSUTF8StringEncoding)!)

I'm new both to swift and pipes, so please tell me if there is something wrong or unrecommended with the code.

like image 207
Yrogirg Avatar asked Sep 28 '22 14:09

Yrogirg


1 Answers

Often is easy to miss a simple sign when we concatenate strings.
In this case you can fix adding \n and + to the line with set output:

 "set output \"1.png\"\n" +

The idea is to create a string as if we were writing in the gnuplot shell, so with each\n we are simulating a new line and with each + we concatenate two or more strings...
this is even the idea that underlie the gnuplot scripting...

Often with gnuplot is cosy to write an external script and to load it with

  load "myscript.gnuplot"

or running it with

 gnuplot -persist myscript.gnuplot

In this way you will have always the possibility to redo your plot or analysis in a blink of an eye, and your result will be always reproducible.

like image 128
Hastur Avatar answered Nov 12 '22 23:11

Hastur