我想在C#应用程序中生成几百个.txt脚本,启动GnuPlot并为我拥有的每个脚本生成.png图形。
我可以使用以下代码从C#启动GnuPlot:
Process gnuPlotProcess = new Process();
gnuPlotProcess.StartInfo = new ProcessStartInfo(@"C:\Program Files\gnuplot\bin\wgnuplot.exe");
gnuPlotProcess.Start();
当我尝试更改当前目录时,出现第一个问题,在开始此过程之前添加以下代码:
gnuPlotProcess.StartInfo.Arguments = "cd '" + scriptsPath + "'";
现在GnuPlot没有开始。
第二个问题,我能够在GnuPlot的默认当前目录上进行测试,是在尝试传递" load' script_xxx.txt'"命令。以下是完整代码(来自Plotting graph from Gunplot in C#的灵感):
Process gnuPlotProcess = new Process();
gnuPlotProcess.StartInfo = new ProcessStartInfo(@"C:\Program Files\gnuplot\bin\wgnuplot.exe");
gnuPlotProcess.StartInfo.RedirectStandardInput = true;
gnuPlotProcess.StartInfo.UseShellExecute = false;
theProcess.Start();
StreamWriter sw = gnuPlotProcess.StandardInput;
sw.WriteLine("load '" + pathToScript + "'");
sw.Flush();
在pathToScript上找到的脚本应该创建一个.png文件,它可以直接从gnuPlot启动。但是从代码来看,没有任何反应。
任何帮助都将不胜感激。
答案 0 :(得分:0)
我希望此代码能为您提供帮助:
int N = 1000;
string dataFile = "data.txt"; // one data file
string gnuplotScript = "gnuplotScript.plt"; // gnuplot script
string pngFile = "trajectory.png"; // output png file
// init values
double x = 0, y = 0;
// random values to plot
Random rnd = new Random();
StreamWriter sw = new StreamWriter(dataFile);
// US output standard
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
// generate data for visualisation
for (int i = 0; i < N; i++)
{
x += rnd.NextDouble() - 0.5;
y += rnd.NextDouble() - 0.5;
sw.WriteLine(x.ToString("F3") + "\t" + y.ToString("F3"));
}
sw.Close();
// you can download it from file
string gnuplot_script = "set encoding utf8\n" +
"set title \"Random trajectory\"\n" +
"set xlabel \"Coordinate X\"\n" +
"set ylabel \"Coordinate Y\"\n" +
"set term pngcairo size 1024,768 font \"Arial,14\"\n" +
"set output \"pngFile\"\n" +
"plot 'dataFile' w l notitle\n" +
"end";
// change filenames in script
gnuplot_script = gnuplot_script.Replace("dataFile", dataFile);
gnuplot_script = gnuplot_script.Replace("pngFile", pngFile);
// write sccript to file
sw = new StreamWriter(gnuplotScript, false, new System.Text.UTF8Encoding(false));
sw.WriteLine(gnuplot_script);
sw.Close();
// launch script
ProcessStartInfo PSI = new ProcessStartInfo();
PSI.FileName = gnuplotScript;
string dir = Directory.GetCurrentDirectory();
PSI.WorkingDirectory = dir;
using (Process exeProcess = Process.Start(PSI))
{
exeProcess.WaitForExit();
}
// OPTION: launch deafault program to see file
PSI.FileName = pngFile;
using (Process exeProcess = Process.Start(PSI))
{
}
您可以使用自己的数据重复此示例,因为您可以多次制作许多png文件