Plotting multiple regression lines through different Y-Intercepts and X-values
Asked Answered
F

1

2

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

Feingold answered 8/6, 2016 at 22:44 Comment(0)
C
2

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.

image

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://mcmap.net/q/1782034/-plotting-multiple-regression-lines-through-different-y-intercepts-and-x-values */
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);
            }
        });
    }
}
Cogan answered 9/6, 2016 at 3:46 Comment(1)
A related example is examined here.Cogan

© 2022 - 2024 — McMap. All rights reserved.