通过不同的Y截距和X值绘制多条回归线 [英] Plotting multiple regression lines through different Y-Intercepts and X-values

查看:91
本文介绍了通过不同的Y截距和X值绘制多条回归线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过线性回归线来分析具有相同斜率的各个独立数据簇。然而,虽然我已经成功地为点本身绘制了不同的颜色并成功地绘制了这些颜色,但我在线上的尝试不起作用。



早些时候,我尝试了一个哈希集,该哈希集通过颜色调出群集,但这导致了这些行进入的顺序出现问题。



在这次尝试中,我尝试通过数字附件链接集群,然后根据它调用行。



第一部分代码并不真正相关,因为我没有更改任何内容,而且该部分按预期工作。它从其他类调用,但由于问题不存在,我不认为显示其他类与我当前的问题相关。



第二个块我的代码就是我迷失的地方。为什么它看起来好像没有编译?没有给出错误,它基本上只被视为幻像代码,好像我的if语句没有被满足甚至初始化它?



下面是第一个可能没有的块相关。第二块代码是我更大的关注点。对不起,我是这些论坛的新手,我不完全确定提出问题的程序。

  package clusters; 

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.HashSet;
import java.util.TreeSet;

import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.FastScatterPlot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.ui.RectangleEdge;

公共类ExtendedFastScatterPlot扩展FastScatterPlot {

/ **
*
* /
private static final long serialVersionUID = 1L;

int []尺寸;
Paint []颜色;
int []形状;

public ExtendedFastScatterPlot(float [] [] data,NumberAxis domainAxis,NumberAxis rangeAxis,int [] sizes,
Paint [] colors,int [] shapes){
super( data,domainAxis,rangeAxis);
this.sizes = sizes;
this.colors = colors;
this.shapes = shapes;
}

@Override
public void render(Graphics2D g2,Rectangle2D dataArea,PlotRenderingInfo info,CrosshairState crosshairState){
// g2.setPaint(Color.BLUE) ;

if(this.getData()!= null){
for(int i = 0; i< this.getData()[0] .length; i ++){
float x = this.getData()[0] [i];
float y = this.getData()[1] [i];
int size = this.sizes [i];
int transX =(int)this.getDomainAxis()。valueToJava2D(x,dataArea,RectangleEdge.BOTTOM);
int transY =(int)this.getRangeAxis()。valueToJava2D(y,dataArea,RectangleEdge.LEFT);
g2.setPaint(this.colors [i]);
if(1 == this.shapes [i]){
g2.fillRect(transX,transY,size,size);
} else {
g2.fillOval(transX,transY,size,size);
}
}
}
g2.setColor(java.awt.Color.red);

try {
double [] lineData = GaussianElimination.calcLines();

/ * HashSet< Paint> paints = new HashSet< Paint>();
for(Paint p:colors){
paints.add(p);
} * /

for(int index = 1; index< lineData.length; index ++){
double slope = lineData [0];

//(油漆p:油漆){

在零件中在下面的代码中,我尝试按编号为每个簇创建一条线,其中Treeset应该模拟新的斜率线以使其贯穿。但是,由于某种原因,就好像代码不存在一样。什么都没有运行,我很好奇它是否与我可能错位的break语句有关?我尝试在index ++之前移动它并在它之后移动它们并返回相同的结果。

  for(int i = 0; i< this.getData()[0] .length; i ++){

TreeSet< Double> xCoords = new TreeSet< Double>();
// if(colors [i] .equals(p)){
xCoords.add((double)this.getData()[0] [i]);
//}
//}
double xleft = xCoords.first();
double xright = xCoords.last();

double yleft = slope * xleft + lineData [index];
double yright = slope * xright + lineData [index];


int txstart =(int)this.getDomainAxis()。valueToJava2D(xleft,dataArea,RectangleEdge.BOTTOM);
int tystart =(int)this.getRangeAxis()。valueToJava2D(yleft,dataArea,RectangleEdge.LEFT);

int txend =(int)this.getDomainAxis()。valueToJava2D(xright,dataArea,RectangleEdge.BOTTOM);
int tyend =(int)this.getRangeAxis()。valueToJava2D(yright,dataArea,RectangleEdge.LEFT);

g2.setPaint(Color.getHSBColor(i /(lineData.length - 1),1,1));
g2.drawLine(txstart,tystart,txend,tyend);

// index ++;
// if(index> = lineData.length)break;
}
} **

} catch(IOException e){
System.out.println(无法打开数据文件);
}
}
}

这是图表

  import java.awt.Dimension; 
import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JFrame;
import org.jfree.chart。*;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.statistics.Regression;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/ ** @see https://stackoverflow.com/a/37716411/230513 * /
公共类RegressionTest {

private static final int N = 16;
private static final Random R = new Random();

private static XYDataset createDataset(){
XYSeries series = new XYSeries(Data);
for(int i = 0; i< N; i ++){
series.add(i,R.nextGaussian()+ i);
}
XYSeriesCollection xyData = new XYSeriesCollection(series);
double [] coefficients = Regression.getOLSRegression(xyData,0);
double b =系数[0]; //拦截
double m =系数[1]; // slope
XYSeries trend = new XYSeries(Trend);
double x = series.getDataItem(0).getXValue();
trend.add(x,m * x + b);
x = series.getDataItem(series.getItemCount() - 1).getXValue();
trend.add(x,m * x + b);
xyData.addSeries(趋势);
返回xyData;
}

私有静态JFreeChart createChart(最终XYDataset数据集){
JFreeChart chart = ChartFactory.createXYLineChart(Test,X,Y,
dataset,PlotOrientation.VERTICAL,true,false,false);
返回图表;
}

public static void main(String [] args){
EventQueue.invokeLater(new Runnable(){
@Override
public void run (){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
XYDataset dataset = createDataset();
JFreeChart chart = createChart(dataset) ;
ChartPanel chartPanel = new ChartPanel(图表){
@Override
public Dimension getPreferredSize(){
返回新维度(640,480);
}
};
f.add(chartPanel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}


I am trying to through a linear regression line through individual separate clusters of data that share the same slope. However, though I have successfully plotted differing colors for the points themselves and graphed those successfully, my attempt at the line is not working.

Earlier I tried a hashset that ran through calling out the clusters by colors but that caused issues with the order in which the lines came in.

In this attempt, I tried to link the clusters through a number attachment and then call the lines based on that.

The first part of the code isn't really relevant as I didn't change anything there and that portion is working as intended. It calls up from other classes but as the problem isn't there, I don't think showing the other classes will be relevant to my current problem.

The second block of my code is where I am lost. Why does it seem as if it isn't compiling? No error is given and it is essentially just considered a phantom code as if my if statement is not being met to even initialize it?

Below is the first block which may not be relevant. The second block of code is my larger concern. Sorry I am new to these forums, I am not completely sure of the procedures of posing a question.

package clusters;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.HashSet;
import java.util.TreeSet;

import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.FastScatterPlot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.ui.RectangleEdge;

public class ExtendedFastScatterPlot extends FastScatterPlot {

    /**
    *
    */
    private static final long serialVersionUID = 1L;

    int[] sizes;
    Paint[] colors;
    int[] shapes;

    public ExtendedFastScatterPlot(float[][] data, NumberAxis domainAxis, NumberAxis rangeAxis, int[] sizes,
            Paint[] colors, int[] shapes) {
        super(data, domainAxis, rangeAxis);
        this.sizes = sizes;
        this.colors = colors;
        this.shapes = shapes;
    }

    @Override
    public void render(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, CrosshairState crosshairState) {
        // g2.setPaint(Color.BLUE);

        if (this.getData() != null) {
            for (int i = 0; i < this.getData()[0].length; i++) {
                float x = this.getData()[0][i];
                float y = this.getData()[1][i];
                int size = this.sizes[i];
                int transX = (int) this.getDomainAxis().valueToJava2D(x, dataArea, RectangleEdge.BOTTOM);
                int transY = (int) this.getRangeAxis().valueToJava2D(y, dataArea, RectangleEdge.LEFT);
                g2.setPaint(this.colors[i]);
                if (1 == this.shapes[i]) {
                    g2.fillRect(transX, transY, size, size);
                } else {
                    g2.fillOval(transX, transY, size, size);
                }
            }
        }
        g2.setColor(java.awt.Color.red);

        try {
            double[] lineData = GaussianElimination.calcLines();

            /*HashSet<Paint> paints = new HashSet<Paint>();
            for (Paint p : colors) {
                paints.add(p);
            }*/

            for (int index = 1; index < lineData.length; index++) {
            double slope = lineData[0];

            //for (Paint p : paints) {

In the part of the code below here, I attempted to create a line for each cluster by number in which in the Treeset should simulate new slope lines for it to run through. However, for some reason, it is as if the code doesn't exist. Nothing is running and I am curious if it has something to do with the break statement that I may have misplaced? I tried moving it before the index++ and after it and both returned the same results.

                for (int i = 0; i < this.getData()[0].length; i++) {

                    TreeSet<Double> xCoords = new TreeSet<Double>();
                    //if (colors[i].equals(p)) {
                        xCoords.add((double) this.getData()[0][i]);
                    //}
                //}
                double xleft = xCoords.first();
                double xright = xCoords.last();

                double yleft = slope * xleft + lineData[index];
                double yright = slope * xright + lineData[index];


                int txstart = (int) this.getDomainAxis().valueToJava2D(xleft, dataArea, RectangleEdge.BOTTOM);
                int tystart = (int) this.getRangeAxis().valueToJava2D(yleft, dataArea, RectangleEdge.LEFT);

                int txend = (int) this.getDomainAxis().valueToJava2D(xright, dataArea, RectangleEdge.BOTTOM);
                int tyend = (int) this.getRangeAxis().valueToJava2D(yright, dataArea, RectangleEdge.LEFT);

                g2.setPaint(Color.getHSBColor(i/(lineData.length - 1), 1, 1 ));
                g2.drawLine(txstart, tystart, txend, tyend);

                //index++;
                //if (index >= lineData.length) break;
                }   
            }**

        } catch (IOException e) {
            System.out.println("Unable to open data files");
        }
    }
}

Here is the Graph Graph Result

解决方案

Absent a complete example, it's hard to say where your current approach fails. The complete example below illustrates the method Regression.getOLSRegression(), which uses ordinary least squares to find the coefficients of a line that estimates a series in an XYDataset. A second series representing the estimate, shown in blue below, is added to the XYDataset.

You can compose more elaborate charts by adding multiple series to your dataset or using multiple renderers in your plot.

import java.awt.Dimension;
import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JFrame;
import org.jfree.chart.*;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.statistics.Regression;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/** @see https://stackoverflow.com/a/37716411/230513 */
public class RegressionTest {

    private static final int N = 16;
    private static final Random R = new Random();

    private static XYDataset createDataset() {
        XYSeries series = new XYSeries("Data");
        for (int i = 0; i < N; i++) {
            series.add(i, R.nextGaussian() + i);
        }
        XYSeriesCollection xyData = new XYSeriesCollection(series);
        double[] coefficients = Regression.getOLSRegression(xyData, 0);
        double b = coefficients[0]; // intercept
        double m = coefficients[1]; // slope
        XYSeries trend = new XYSeries("Trend");
        double x = series.getDataItem(0).getXValue();
        trend.add(x, m * x + b);
        x = series.getDataItem(series.getItemCount() - 1).getXValue();
        trend.add(x, m * x + b);
        xyData.addSeries(trend);
        return xyData;
    }

    private static JFreeChart createChart(final XYDataset dataset) {
        JFreeChart chart = ChartFactory.createXYLineChart("Test", "X", "Y",
            dataset, PlotOrientation.VERTICAL, true, false, false);
        return chart;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                XYDataset dataset = createDataset();
                JFreeChart chart = createChart(dataset);
                ChartPanel chartPanel = new ChartPanel(chart) {
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(640, 480);
                    }
                };
                f.add(chartPanel);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
}

这篇关于通过不同的Y截距和X值绘制多条回归线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆