2013-10-17 36 views
2

我在java中使用gnuplot,并且有这个问题一直让我发疯。基本上,我使用这个功能,在同一个情节绘制两个双[]数组 -与java一起使用gnuplot

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之前读取和写入文件的方式有关。有人可以帮助我改进这种绘图功能,所以我没有看到这种奇怪的行为?

+1

可能是某种竞争条件,请参阅[Java:等待执行过程直到它退出](http://stackoverflow.com/q/12448882/2604213)。 – Christoph

+0

谢谢克里斯托弗。这正是问题所在。每次调用此函数后,我都添加了一个Thread.sleep(10),问题似乎已解决。 –

回答

3

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

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

这应该等待gnuplot命令完成。

1

你可以尝试JavaGnuplotHybrid:

这里是绘制双[]数组代码:

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); 
} 

enter image description here

这是非常简单和直接。有关更多详细信息,请参阅:https://github.com/mleoking/JavaGnuplotHybrid