forked from martinruenz/gnuplot-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample2.cpp
More file actions
93 lines (80 loc) · 1.93 KB
/
example2.cpp
File metadata and controls
93 lines (80 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "gnuplot.h"
#include <chrono>
#include <thread>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <stdexcept>
namespace fs = std::filesystem;
std::ofstream getFile( const fs::path& path, bool append = false ){
std::ofstream of;
of.open( path.c_str(),
append ? std::ios_base::app : std::ios_base::trunc
);
if (of){
return of;
}
throw std::runtime_error(
"Could not write to file \"" + path.string() + "\"!"
);
}
void writeLine(
const std::string& line,
const fs::path& path,
bool append = false
){
std::ofstream of { getFile(path, append) };
of << line << '\n';
of.close();
}
class LineWriter {
private:
fs::path m_path;
bool m_append {false};
public:
LineWriter(const fs::path& p) : m_path {p} {}
void append(bool b){ m_append = b; }
void write( const std::string& str ){
writeLine(str, m_path, m_append);
}
};
int main(){
const fs::path wd { fs::current_path().lexically_normal() };
double xmin {0}, xmax {5}, xstep {0.1};
int sleep_ms {100};
using Func = double (*)(double);
Func fn { std::sin };
std::string outf { "outf.dat" };
fs::path outp { wd / outf };
LineWriter lw {outp};
lw.write("title_x title_y");
lw.append(true);
std::stringstream plotCommand; plotCommand
<< "plot "
<< '\"' << outf << '\"' // file
<< " using 1:2" // cols
<< " with lines" // style
;
std::stringstream rng; rng
<< "set xrange [" << xmin << ':' << xmax << ']';
GnuplotPipe gp;
gp.open();
gp.sendLine( "cd \"" + wd.string() + "\"" );
gp.sendLine( "set key autotitle columnhead" );
gp.sendLine( rng.str() );
bool first {true};
for ( double x{xmin}; x<xmax; x+=xstep ){
lw.write( std::to_string(x) + " " + std::to_string( std::sin(x) ) );
if (first){
first = false;
gp.sendLine( plotCommand.str() );
gp.flush();
} else {
gp.sendLine("replot");
gp.flush();
}
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
}
return 0;
}