2016-04-29 123 views
-1

我有一個編碼問題,我想繪製值(x和y)並計算線性迴歸並將其繪製在imageJ中。誰能幫忙?有沒有辦法在ImageJ中繪製線性迴歸?

我想這

public class Plot implements PlugIn { 
    public void run(String arg) { 
     if (IJ.versionLessThan("1.27t")) 
      return; 

     float[] x = {0.375f, 0.75f, 1.5f, 2.25f, 3f,3.75f,4.5f,4.75f,5f}; 
     // x-coordinates 
     float[] y = {123f,456f,5678f,4567f,4567f,5678f,2345f,4563f,2345f}; 
     // y-coordinates 
     float[] e = {.8f,.6f,.5f,.4f,.3f,.5f,.6f,.7f,.8f}; 
     // error bars 

     PlotWindow plot = new PlotWindow("Example Plot","x-axis","y-axis",x,y); 
     plot.setLimits(0, 5.5, 0, 6000); 
     plot.addErrorBars(e); 

     // add a second curve 
     float x2[] = {.4f,.5f,.6f,.7f,.8f}; 
     float y2[] = {4,3,3,4,5}; 

     int N=9; 
     double sumx = 0.0, sumy = 0.0, sumx2 = 0.0; 
     for (int i = 0; i < N; i++) 
      sumx += x[i]; 
     for (int i = 0; i < N; i++) 
      sumx2 += x[i]*x[i]; 
     for (int i = 0; i < N; i++) 
      sumy += y[i]; 
     double xbar = sumx/N; 
     double ybar = sumy/N; 

     // second pass: compute summary statistics 
     double xxbar = 0.0, yybar = 0.0, xybar = 0.0; 
     for (int i = 0; i < N; i++) { 
      xxbar += (x[i] - xbar) * (x[i] - xbar); 
      yybar += (y[i] - ybar) * (y[i] - ybar); 
      xybar += (x[i] - xbar) * (y[i] - ybar); 
     } 
     slope = xybar/xxbar; 
     intercept = ybar - slope * xbar; 

     // more statistical analysis 
     double rss = 0.0;  // residual sum of squares 
     double ssr = 0.0;  // regression sum of squares 
     for (int i = 0; i < N; i++) { 
      double fit = slope*x[i] + intercept; //calculating fit 
      rss += (fit - y[i]) * (fit - y[i]); 
      ssr += (fit - ybar) * (fit - ybar); //calculating ssr 
     } 
    } 
} 
+0

什麼不起作用?這段代碼是不是做你期望的事情? – jessehouwing

回答

0

以下Groovy script(這是非常類似於Java,可以從ImageJ中的Script editor直線運行)演示瞭如何使用ij.gui.Plotij.measure.CurveFitter類來生成一個陰謀迴歸線:

import ij.gui.Plot 
import ij.measure.CurveFitter 

x = [0.375d, 0.75d, 1.5d, 2.25d, 3d,3.75d,4.5d,4.75d,5d]; 
// x-coordinates 
y = [123d,456d,5678d,4567d,4567d,5678d,2345d,4563d,2345d]; 
// y-coordinates 

plot = new Plot("Example Plot","x-axis","y-axis"); 
plot.addPoints(x,y,Plot.LINE) 
plot.setLimits(0, 5.5, 0, 6000); 

cf = new CurveFitter((double[]) x, (double[]) y) 
cf.doFit(CurveFitter.STRAIGHT_LINE) 

yfit = [] 
for (cx in x) { 
    yfit.add(cf.f(cx)) 
} 

plot.addPoints(x, yfit, Plot.LINE) 
plotwindow = plot.show() 

幾個建議:

  • 不要叫你自己的班級Plot,因爲你的代碼的讀者可能會與ij.gui.Plot混淆。
  • 使用ij.gui.Plot而不是ij.gui.PlotWindow;前者提供更多的功能。
  • 當有工具可用時,不要做手動迴歸。
  • 對於特定於ImageJ and SciJava APIs的問題,最好提出的地方是ImageJ forum
相關問題