2013-10-17 34 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