如何在 C++ 中绘制 gsl_vector?

How to plot gsl_vector in C++?

有没有方便的方法或库在 C++ 中绘制 gsl_vector?例如,如果我有两个 gsl 向量,我想为同一个图形在 x 轴上绘制一个,在 y 轴上绘制另一个。

经过一些研究,我了解到在 C++ 中无法直接绘制 gsl_vector。但是,我使用 gnuplot 编写了一个解决方法(几乎与 bitmask 建议的方法一样),它解决了我的问题。因此,我发布了我自己问题的答案。

以下是我的解决方案:

#include <stdio.h>
#include <gsl/gsl_vector.h>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>

void plot(const gsl_vector *x, const gsl_vector *y);

using namespace std;

int main ()
{
  int i;
  gsl_vector * x = gsl_vector_alloc (10);
  gsl_vector * y = gsl_vector_alloc (10);

  for (i = 0; i < 10; i++)
    {
      gsl_vector_set (x, i, i);
      gsl_vector_set (y, i, exp(i));
    }
  
  plot(x, y);

  gsl_vector_free (x);
  gsl_vector_free (y);
  return 0;
}


void plot(const gsl_vector *x, const gsl_vector *y)
{
  string command_filename = "commands.txt";
  ofstream command;
  string data_filename = "data.txt";
  ofstream data;
  int j;
  string plot_filename = "plot.png";

  cout << "\n";
  cout << "plot:\n";
  cout << "  Write command and data files that can be used\n";
  cout << "  by gnuplot for a plot.\n";

//  Create the data file.

  data.open ( data_filename.c_str ( ) );

  for ( j = 0; j < x->size; j++ )
  {
    data << "  " << gsl_vector_get(x, j)
         << "  " << gsl_vector_get(y, j) << "\n";
  }

  data.close ( );

  cout << "\n";
  cout << "  plot: data stored in '"
       << data_filename << "'\n";
       
//  Create the command file.

  command.open ( command_filename.c_str ( ) );

  command << "# " << command_filename << "\n";
  command << "#\n";
  command << "# Usage:\n";
  command << "#  gnuplot < " << command_filename << "\n";
  command << "#\n";
  command << "set term png\n";
  command << "set output '" << plot_filename << "'\n";
  command << "set xlabel 'X'\n";
  command << "set ylabel 'Y'\n";
  command << "set title 'Plot using gnuplot'\n";
  command << "set grid\n";
  command << "set style data lines\n";
  command << "plot '" << data_filename << "' using 1:2 with lines\n";
  command << "quit\n";

  command.close ( );

  cout << "  plot: plot commands stored in '"
       << command_filename << "'\n";

  return;
}

main()中,我生成了两个gsl向量,然后将它们传递给绘图函数。在绘图函数中,我将这些向量写入一个名为 data.txt 的文件中。然后我生成一个命令文件 commands.txt,然后 gnuplot 可以使用 data.txt 文件读取该文件。

在运行上面的代码之后,我手动写了如下命令:

gnuplot < commands.txt

在 terminal/console 中绘制向量,产生以下图: