C++ and gnuplot - c++

This is my first post and I'm quite a novice on C++ and compiling in general.
I'm compiling a program which requires some graphs to be drawn. The program create a .dat file and then i should open gnuplot and write plot '.dat'. That's fine.
Is there a way to make gnuplot automatically open and show me the plot I need? I should use some system() function in the code to call gnuplot but how can I make him plot what I need?
Sorry for my non-perfect English :s
Thanks for the attention anyway!

Depending on your OS, you might be able to use popen(). This would let you spawn a gnuplot process and just just write to it like any other FILE*.
If you have datapoints to plot, you can pass them inline with the plot "-" ... option. Similarly, you may want to explore set data style points/lines/linespoints/etc options.
Without pause or persist, gnuplot will terminate upon end-of-input-stream. In your example case, that would be when the end of the file is reached.
To produce (write) an output file (graph), use:
set terminal png small
set output "filename.png"
There's lots of options to set terminal. Png is usually there. If not, perhaps gif, tiff, or jpeg?
Watch out for overwriting the file!
You may want to use set size 2,2 to make a larger graph. Some set terminal variants also allow you to specify the size.

I'm learning this today too. Here is a small example I cooked up.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv) {
ofstream file("data.dat");
file << "#x y" << endl;
for(int i=0; i<10; i++){
file << i << ' ' << i*i << endl;
}
file.close();
return 0;
}
Save that as plot.cpp and compile that with g++:
g++ plot.cpp -o plot
Run the program to create the .dat file:
./plot
Save the following gnuplot script as plot.plt:
set terminal svg enhanced size 1000 1000 fname "Times" fsize 36
set output "plot.svg"
set title "A simple plot of x^2 vs. x"
set xlabel "x"
set ylabel "y"
plot "./data.dat" using 1:2 title ""
Run the script with gnuplot to generate your .svg file:
gnuplot plot.plt
The resulting plot will be in plot.svg. If you leave out the first couple lines that specify the output, it will render in a window. Have fun!

Sometimes it is as easy as one may think
gnuplot file
where file is neither your data nor your result file, but a file with the command you would type in the commandline. Just enter there your commands you need (either constant file you have or generate it).
After executing all commands in that file gnuplot exits.

Yes you can. You can make a file that has the commands you would otherwise type in to set up the plot and open gnuplot running from that file. This link has an article that explains how to do it. You can also output to an EPS or other graphical output formats and display the plot using another widget that reads in the file.

You may need to use the '-persist' flag to the command. I know that on *nix systems, this flag is required if you want the plot window to remain after the gnuplot process has completed and exited.
gnuplot -persist commands.gp
Also, you can put as many gnuplot commands as you like in the file. The file acts sort of like a batch script in this regard.

You might need to add a line
pause -1
This will show the plot until return has been pressed.
What you are probably seeing is that gnuplot runs and exits before the plot has time to be displayed.

You might need to set a terminal type. Read the gnuplot documentation about that.

Related

Commands in GWBASIC

I am using GWBASIC and cannot figure out a few things. Like, when I'm saving a program after running it with F4, it says: File not found.
Secondly, when I'm using auto command it shows * with line numbers.
Finally, if I want to take program and its output's print on paper, what should I do?
I am using GWBASIC and cannot figure out a few things. Like, when I'm
saving a program after running it with F4, it says: File not found.
Try saving like this:
SAVE"myprog.bas",a
Secondly, when I'm using auto command it shows * with line numbers.
The star (*) on a line means that line already exists and you are overwriting it.
If you use the command NEW to wipe-out the program from memory before running 'auto', you won't see those stars on lines.
Finally, if I want to take program and its output's print on paper,
what should I do?
1) Save the program as a text file:
SAVE"myprog.bas",a
2) Open the file 'myprog.bas' with a text editor (like Notepad++).
3) Print it.
To print a GW-BASIC program, use the LIST command.
The optional , filename parameter specifies the output for the listing. It could be to a file (e.g. to dump the text so another program can load it), or it could be to a printer device (e.g. LPT1:).
So this should work:
LIST ,LPT1:
See also https://robhagemans.github.io/pcbasic/doc/1.2/#LIST

Plot values in .m file from C++

I have looked extensively in the net, yet not found exactly what I want.
I have a big simulation program that outputs results in a MATLAB M-file (let's call it res.m) and I want to plot the results visually.
I want to start the simulation with C++ many times in a row and therefore want to automatize the plotting of the results.
I come up to two options:
Execute from C++ an Octave or MATLAB script that generates the graph.
-> Haven't found anyone who managed to do so
Use the Octave source files to read the res.m file and output them after with whatever plotting C++ tool.
-> Theoretically possible but I get lost in those files
Is someone able to solve this? Or has a better, easier approach?
The answer is to execute through the terminal.
I didn't manage to actually run a octave script from my c++ program directly, but there is a way around messing with/through the terminal and a extra Octave file. I used in my cpp:
string = "octave myProgr.m"
const char *command = str.c_str();
system(command);
myProgr.m is the script that plots the res.m file

New to C++, I do not understand how to display output in a .txt file

I am very new to C++. I have my code and it displays my desired output in a win32 console.
However, my Instructor wants the output to be run through a .txt file. We have done this before with a program that had input already written within the coding.
ex.
cout << "example1....example2";
We achieved this with his exact instructions:
*1) Probably the easiest way to obtain a hard copy of the generated
program output on a Microsoft Windows platform is to run your
program from a command prompt, redirecting the output to a file.
The command line syntax would like like this:
lab1prog >lab1.txt*
My problem, however, is that I did this again for lab2 and redirected the output to lab2.txt but I need user input for this time around. When I run the lab2.exe file, my lab2.txt file outputs my "cout" statement and waits for input but I cannot enter input through a .txt file.
Please help if you can.
When you redirect the output of the program with
lab1prog >lab1.txt
then the user is still able to input data. The only problem is that she doesn't know when to enter what data. This is usually done by prompt outputs that are hidden whith the >lab1.txt.
To circumvent the problem you could abuse the error output what is not redirected with the command above.
cerr << "prompt";
To avoid this abuse you should use a "tee" program like wintee instead of redirecting with a simple >lab1.txt.
If it's acceptable to get the input from a file instead from the user you can use the input redirection.
labprog1 <input.txt >lab1.txt
If you specifically want to use a text file as input into your program, the easiest way (as Kamil Mikolajczyk mentioned) is to run it this way:
> lab1prog >lab1.txt <input.txt
On the other hand, if you need to run the program as it is, but have complete control over what to output into the file, I'd suggest using a file handle. Check out this question on how to use file handles. You could even duplicate the output on the command prompt and the file when you want by outputting it as:
fout << "My output";
cout << "My output";
You can as well output the user input into your output file for your convenience.

Octave plot from Qt C++ application

I have a QT C++ application that runs the Octave program using QProcess. I am able to communicate with it by reading the standard output/error and writing to it's standard input using write method (for example: octave->write("5 + 5\n");).
As I told you I get response from octave (from the above example I get "ans = 10").
However, when the command I write to Octave standard input has a "plot" (for example, a simple plot([1 2 3 4 5]);), the actual graphic is never shown. I know Octave runs gnuplot, I have it installed, and gnuplot_x11 too. I even change the gnuplot binary path in my Octave process by executing gnuplot_binary("/usr/bin/gnuplot"); from MY APPLICATION. I know it runs good because if I retrieve the new value I get it right. But I don't know why Octave doesn't show the graphic.
Here I start octave:
QStringList arguments;
arguments << "--persist";
octave->setProcessChannelMode(QProcess::MergedChannels);
octave->start("/usr/bin/octave", arguments);
Here I write commands to octave process:
if (octave->state() == QProcess::Running) {
QString command = widget.txtInput->toPlainText();
if (command.isEmpty()) {
return;
}
command += "\n";
octave->write(command.toAscii());
}
With this I print the octave response to a text edit:
widget.txtOutput->append(octave->readAll() + "\n");
And finally, I use this when the octave process starts:
QString gnuplot_path(tr("\"/usr/bin/gnuplot\""));
QString gnuplot_cmd(tr("gnuplot_binary(%1)\n").arg(gnuplot_path));
octave->write(gnuplot_cmd.toAscii());
I will appreciate any help you could give me.
Thanks in advance.
Octave, like Matlab, can be run in batch mode to perform computations without graphical UI. I assume that Octave detects that it is not run from an interactive session, and therefore automatically goes into batch mode. You would expect Octave to suppress graphical output (e.g. gnuplot output) when being in batch mode.
Try to force Octave into interactive mode by using the --interactive command line option:
http://www.gnu.org/software/octave/doc/interpreter/Command-Line-Options.html
I know you probably already solved your problem but this might be helpful for other...
You can try to add a command to save your plot in a temporary folder in your octave request.
Then display the graph in your ap

creating a pipe and writing to gnuplot terminal from c++

I am trying to call the gnuplot from c++. I am using wgnuplot for Windows and VS2005 c++.
The following statement works because it opens the gnuplot terminal
FILE *p = _popen("wgnuplot -persist","w");
But I cannot write anything there. My terminal is still blank even after running the following code.
fprintf(p, "set terminal x11 enhanced\n"); //set appropriate output terminal for the plot
fprintf(p, "set xlabel 'N'\n");//set xlabel
fprintf(p, "set ylabel 'error'\n");//set ylabel
Could you please tell me what might be the problem, i.e. why the terminal is blank and fprintf() doesn't seem to work?
Thanks,
Boris
Check that FILE pointer is not NULL:
if(!p)
// _popen() has failed...
I do not know if that helps you, but this is my approach of executing gnuplot from my C programs:
I create a template file (usually I do not delete it, so that it is easier to troubleshoot), where all the gnuplot commands are are scripted in.
I run gnuplot with
system("gnuplot <TemplateFile>")
If you are only interested in creating a plot, that his would do the job. If you are explicitly interested in the approach you described above then just disregard this posting ;)
Cherio Woltan