繁体   English   中英

如何在 C++ 中使用 plot gsl_vector?

[英]How to plot gsl_vector in C++?

gsl_vector是否有方便的方法或库? 例如,如果我有两个 gsl 向量,我想 plot 一个在 x 轴上,另一个在 y 轴上以获得相同的图形。

经过一番研究,我知道在 C++ 中不能直接使用gsl_vector 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 向量,然后将它们传递给 plot function。 在 plot function 中,我将这些向量写入一个名为data.txt的文件中。 然后我生成一个命令文件commands.txt ,然后 gnuplot 可以使用data.txt文件读取该文件。

运行上面的代码后,我手动编写以下命令:

gnuplot < commands.txt

在终端/控制台到 plot 向量,产生以下 plot:

阴谋

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM