Gnuplot - update graph every second
I want to draw a graph that changes every second. I am using below code, it changes the graph periodically. But each iteration does not preserve the previous iteration points. How should I do it? There is only one point in every second. But I want to draw a graph with historical data.
FILE *pipe = popen("gnuplot -persist", "w");
// set axis ranges
fprintf(pipe,"set xrange [0:11]\n");
fprintf(pipe,"set yrange [0:11]\n");
int b = 5;int a;
for (a=0;a<11;a++) // 10 plots
{
fprintf(pipe,"plot '-' using 1:2 \n"); // so I want the first column to be x values, second column to be y
// 1 datapoints per plot
fprintf(pipe, "%d %d \n",a,b); // passing x,y data pairs one at a time to gnuplot
fprintf(pipe,"e \n"); // finally, e
fflush(pipe); // flush the pipe to update the plot
usleep(1000000);// wait a second before updating again
}
// close the pipe
fclose(pipe);
+3
source to share
1 answer
A few comments:
- The default in gnuplot is that x data belongs to the first column and y data belongs to the second. You don't need a specification
using 1:2
. - If you need 10 graphs, the loop shape
for
should befor (a = 0; a < 10; a++)
.
There is no good way in gnuplot to add a string that already exists, so it makes sense to store your values ββto be displayed in an array and loop through that array:
#include <vector>
FILE *pipe = popen("gnuplot -persist", "w");
// set axis ranges
fprintf(pipe,"set xrange [0:11]\n");
fprintf(pipe,"set yrange [0:11]\n");
int b = 5;int a;
// to make 10 points
std::vector<int> x (10, 0.0); // x values
std::vector<int> y (10, 0.0); // y values
for (a=0;a<10;a++) // 10 plots
{
x[a] = a;
y[a] = // some function of a
fprintf(pipe,"plot '-'\n");
// 1 additional data point per plot
for (int ii = 0; ii <= a; ii++) {
fprintf(pipe, "%d %d\n", x[ii], y[ii]) // plot `a` points
}
fprintf(pipe,"e\n"); // finally, e
fflush(pipe); // flush the pipe to update the plot
usleep(1000000);// wait a second before updating again
}
// close the pipe
fclose(pipe);
Of course, you probably want to avoid hardcoded magic numbers (like 10), but this is just an example.
+1
source to share