2

我在 java 中使用 gnuplot,这个问题一直让我发疯。基本上,我使用这个函数在同一个图上绘制两个 double[] 数组 -

public static void plot(String filename,double[] ua1,double[] ua2) throws IOException{
    if(ua1.length==0 | ua2.length==0){
        System.out.println("This one had no data - " + filename);
        return;
    }
    File fold1 = new File("old");
    if(fold1.exists()){
        boolean a = fold1.delete();
        if(!a)System.out.println("Houstoonnn!!!");
    }
    fold1 = new File("new");
    if(fold1.exists()){
        boolean a = fold1.delete();
        if(!a)System.out.println("Not deleted!!!");
    }
    FileWriter outF1 = new FileWriter("old");
    FileWriter outF2 = new FileWriter("new");
    PrintWriter out1 = new PrintWriter(outF1);
    PrintWriter out2 = new PrintWriter(outF2);
    for(int j=0;j < ua1.length;j++){
        out1.println(ua1[j]);
        out2.println(ua2[j]);
    }
    out1.close();
    out2.close();
    File fold2 = new File("auxfile.gp");
    try{//If the file already exists, delete it..
        fold2.delete();
    }
    catch(Exception e){}
    FileWriter outF = new FileWriter("auxfile.gp");
    PrintWriter out = new PrintWriter(outF);
    out.println("set terminal gif");
    out.println("set output \""+ filename+".gif\"");
    out.print("set title " + "\""+filename+"\"" + "\n");
    out.print("set xlabel " + "\"Time\"" + "\n");
    out.print("set ylabel " + "\"UA\"" + "\n");
    out.println("set key right bottom");
    out.println("plot \"old\" with linespoints,\"new\" with linespoints");
    out.close();// It's done, closing document.
    Runtime.getRuntime().exec("gnuplot auxfile.gp");
}

这个想法是将两个双打都写入单独的文件并用 gnuplot 绘制它们。当这个函数只被调用一次时,它工作得很好。但是当我从一个循环中重复调用它时,我看到一些空文件正在生成,而其他文件只是错误的(例如,图会减少一些时间,而我知道它们不能)。在某些情况下它确实可以正常工作,所以这是非常随机的。我知道这与我在调用 gnuplot 之前读取和写入文件的方式有关。有人可以帮我改进这个绘图功能,这样我就看不到这种奇怪的行为了吗?

4

2 回答 2

3

这看起来像是某种竞争条件,请参阅Java: wait for exec process until it exits。尝试以下操作:

Runtime commandPrompt = Runtime.getRuntime();
commandPrompt.exec("gnuplot auxfile.gp");
commandPrompt.waitFor();

这应该等待gnuplot命令完成。

于 2013-10-17T20:10:22.123 回答
1

你可以试试 JavaGnuplotHybrid:

这是绘制 double[] 数组的代码:

public void plot2d() {
    JGnuplot jg = new JGnuplot();
    Plot plot = new Plot("") {
        {
            xlabel = "x";
            ylabel = "y";
        }
    };
    double[] x = { 1, 2, 3, 4, 5 }, y1 = { 2, 4, 6, 8, 10 }, y2 = { 3, 6, 9, 12, 15 };
    DataTableSet dts = plot.addNewDataTableSet("2D Plot");
    dts.addNewDataTable("y=2x", x, y1);
    dts.addNewDataTable("y=3x", x, y2);
    jg.execute(plot, jg.plot2d);
}

在此处输入图像描述

它非常简单明了。更多详情:https ://github.com/mleoking/JavaGnuplotHybrid

于 2014-04-02T19:30:12.410 回答