Esempio n. 1
0
def regression(data, regtype=0):
    xAxis = NumberAxis("x")
    xAxis.setAutoRangeIncludesZero(False)
    yAxis = NumberAxis("y")
    yAxis.setAutoRangeIncludesZero(False)

    series = XYSeries("values")
    xmax = xmin = None
    for (x, y) in data:
        series.add(x, y)
        if xmax is None:
            xmax = xmin = x
        else:
            xmax = max(xmax, x)
            xmin = min(xmin, x)

    dataset = XYSeriesCollection()
    dataset.addSeries(series)

    renderer1 = XYDotRenderer()
    plot = XYPlot(dataset, xAxis, yAxis, renderer1)

    if regtype == 1:
        coefficients = Regression.getPowerRegression(dataset, 0)
        curve = PowerFunction2D(coefficients[0], coefficients[1])
        regdesc = "Power Regression"
    else:
        coefficients = Regression.getOLSRegression(dataset, 0)
        curve = LineFunction2D(coefficients[0], coefficients[1])
        regdesc = "Linear Regression"

    regressionData = DatasetUtilities.sampleFunction2D(
        curve, xmin, xmax, 100, "Fitted Regression Line")

    plot.setDataset(1, regressionData)
    renderer2 = XYLineAndShapeRenderer(True, False)
    renderer2.setSeriesPaint(0, Color.blue)
    plot.setRenderer(1, renderer2)

    jfchart = JFreeChart(regdesc, JFreeChart.DEFAULT_TITLE_FONT, plot, True)

    chart = Chart(jfchart)
    chart.coeffs = coefficients

    return chart
Esempio n. 2
0
def regression(data, regtype=0):
  xAxis = NumberAxis("x")   
  xAxis.setAutoRangeIncludesZero(False)   
  yAxis = NumberAxis("y")   
  yAxis.setAutoRangeIncludesZero(False)   
   
  series = XYSeries("values"); 
  xmax = xmin = None       
  for (x,y) in data:
    series.add(x, y);
    if xmax is None:
      xmax = xmin = x
    else:
      xmax = max(xmax, x)
      xmin = min(xmin, x)
            
  dataset = XYSeriesCollection()
  dataset.addSeries(series);

  renderer1 = XYDotRenderer()
  plot = XYPlot(dataset, xAxis, yAxis, renderer1)   
      
  if regtype == 1:
    coefficients = Regression.getPowerRegression(dataset, 0)
    curve = PowerFunction2D(coefficients[0], coefficients[1])
    regdesc = "Power Regression"    
  else:
    coefficients = Regression.getOLSRegression(dataset, 0)   
    curve = LineFunction2D(coefficients[0], coefficients[1])
    regdesc = "Linear Regression"   
    
  regressionData = DatasetUtilities.sampleFunction2D(curve, xmin, xmax, 100, 
    "Fitted Regression Line")   
           
  plot.setDataset(1, regressionData)   
  renderer2 = XYLineAndShapeRenderer(True, False)   
  renderer2.setSeriesPaint(0, Color.blue)   
  plot.setRenderer(1, renderer2)
           
  jfchart = JFreeChart(regdesc, JFreeChart.DEFAULT_TITLE_FONT, plot, True);
    
  chart = Chart(jfchart)          
  chart.coeffs = coefficients
    
  return chart
Esempio n. 3
0
    def updateChartDataset(self, drawLabels=True):
        dataset = XYSeriesCollection()
        # self._calculateConfArea()
        # dataset.addSeries(self.confArea)
        dataset.addSeries(self.markers)
        plot = self.chart.getPlot()
        rangeAxis = plot.getRangeAxis()
        domainAxis = plot.getDomainAxis()
        rangeAxis.setRange(self.minY, self.maxY)  # change
        domainAxis.setRange(self.minX, self.maxX)
        # plot.setBackgroundPaint(Color.lightGray);
        # plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        # plot.setDomainGridlinePaint(Color.white);
        # plot.setRangeGridlinePaint(Color.white);

        markerRenderer = XYLineAndShapeRenderer(False, True)
        # print self.markerColor
        markerRenderer.setSeriesPaint(0, self.markerColor)
        markerRenderer.setSeriesShape(0, Ellipse2D.Double(-3, -3, 6, 6))
        # markerRenderer.setToolTipGenerator(FDistToolTipGenerator(self.pointNames))
        plot.setRenderer(0, markerRenderer)
        plot.setDataset(0, dataset)
        dataset = XYSeriesCollection()
        if self.drawCI:
            dataset = YIntervalSeriesCollection()
            CIRenderer = DeviationRenderer(True, False)
            # CIRenderer.setOutline(True)
            # CIRenderer.setRoundXCoordinates(True)
            dataset.addSeries(self.bottom)
            dataset.addSeries(self.top)
            dataset.addSeries(self.limit)
            CIRenderer.setSeriesFillPaint(0, self.balColor)
            CIRenderer.setSeriesFillPaint(1, self.neuColor)
            CIRenderer.setSeriesFillPaint(2, self.posColor)
            CIRenderer.setSeriesPaint(0, self.balColor)
            CIRenderer.setSeriesPaint(1, self.neuColor)
            CIRenderer.setSeriesPaint(2, self.posColor)
            plot.setDataset(1, dataset)
            plot.setRenderer(1, CIRenderer)
        plot.setDataset(1, dataset)
        if drawLabels:
            self.drawLabels()
Esempio n. 4
0
    def updateChartDataset(self, drawLabels=True):
        dataset = XYSeriesCollection()
        #self._calculateConfArea()
        #dataset.addSeries(self.confArea)
        dataset.addSeries(self.markers)
        plot = self.chart.getPlot()
        rangeAxis = plot.getRangeAxis()
        domainAxis = plot.getDomainAxis()
        rangeAxis.setRange(self.minY, self.maxY)  #change
        domainAxis.setRange(self.minX, self.maxX)
        #plot.setBackgroundPaint(Color.lightGray);
        #plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        #plot.setDomainGridlinePaint(Color.white);
        #plot.setRangeGridlinePaint(Color.white);

        markerRenderer = XYLineAndShapeRenderer(False, True)
        #print self.markerColor
        markerRenderer.setSeriesPaint(0, self.markerColor)
        markerRenderer.setSeriesShape(0, Ellipse2D.Double(-3, -3, 6, 6))
        #markerRenderer.setToolTipGenerator(FDistToolTipGenerator(self.pointNames))
        plot.setRenderer(0, markerRenderer)
        plot.setDataset(0, dataset)
        dataset = XYSeriesCollection()
        if self.drawCI:
            dataset = YIntervalSeriesCollection()
            CIRenderer = DeviationRenderer(True, False)
            # CIRenderer.setOutline(True)
            # CIRenderer.setRoundXCoordinates(True)
            dataset.addSeries(self.bottom)
            dataset.addSeries(self.top)
            dataset.addSeries(self.limit)
            CIRenderer.setSeriesFillPaint(0, self.balColor)
            CIRenderer.setSeriesFillPaint(1, self.neuColor)
            CIRenderer.setSeriesFillPaint(2, self.posColor)
            CIRenderer.setSeriesPaint(0, self.balColor)
            CIRenderer.setSeriesPaint(1, self.neuColor)
            CIRenderer.setSeriesPaint(2, self.posColor)
            plot.setDataset(1, dataset)
            plot.setRenderer(1, CIRenderer)
        plot.setDataset(1, dataset)
        if drawLabels:
            self.drawLabels()
Esempio n. 5
0
def scatter(data,x=None,y=None,**kwargs):
    ''' Creates a scatter plot comparing two elements. At minimum, takes a collection of data.
        The second and third arguments, if they exist, are treated as the two elements to 
        compare. If these arguments do not exist, the first two elements in the list are 
        compared. If an optional regress=True argument is present, superimposes a linear 
        regression for each series and prints some related info (R-value etc). 
        Note that scatter plots can be zoomed with the mouse. Returns the plot object in
        case you want to customize the graph in some way. Takes an optional showMissing argument 
        which determines whether missing values (-9999.0) should be displayed. 
        Examples: scatter(data), scatter(data,"tmin","tmax",regress=True)
    '''
    from org.jfree.data.xy import XYSeriesCollection,XYSeries
    from org.jfree.data import UnknownKeyException
    from org.jfree.chart import ChartFactory,ChartFrame
    from org.jfree.chart.plot import PlotOrientation,DatasetRenderingOrder
    from org.jfree.chart.renderer.xy import XYLineAndShapeRenderer
    from java.awt import Color
    
    regress=kwargs.get('regress',False)
    showMissing=kwargs.get('showMissing',False)
    
    # Try to be flexible about element parameters
    if x is not None: x = findElement(x).name
    if y is not None: y = findElement(y).name

    # Create a dataset from the data
    collection = XYSeriesCollection()
    for ob in data.groupedByObservation().items():
        key,values = ob
        name = str(key[0])
        if x==None:
            x = values[0].element.name
        try:
            xFact = (i for i in values if i.element.name == x).next()
        except StopIteration: # missing value
            continue
        xval  = xFact.value
        if xval in missingValues and not showMissing: continue  
        if y==None:
            try:
                y = values[1].element.name
            except IndexError:
                raise Exception("Error! Your data request returned only 1 value per observation. " 
                                "Must have 2 values to generate a scatter plot.")
        try:
            yFact = (i for i in values if i.element.name == y).next()
        except StopIteration: # missing value
            continue
        yval  = yFact.value
        if yval in missingValues and not showMissing: continue  
        
        try: 
            series = collection.getSeries(name)
        except UnknownKeyException:
            collection.addSeries(XYSeries(name))
            series = collection.getSeries(name)
        
        series.add(float(xval),float(yval))

    # Create chart from dataset        
    chart = ChartFactory.createScatterPlot( "", x, y, collection, PlotOrientation.VERTICAL,
                                            True, True, False );
    plot = chart.getPlot()
    frame = ChartFrame("Scatter Plot", chart);
    frame.pack();
    frame.setVisible(True);

    # Superimpose regression if desired
    if regress:
        regressioncollection = XYSeriesCollection()
        for series in collection.getSeries():
            regression = _getregression(series)
            x1 = series.getMinX()
            y1 = regression.predict(x1)
            x2 = series.getMaxX()
            y2 = regression.predict(x2)
            regressionseries = XYSeries(series.getKey())
            regressionseries.add(float(x1),float(y1))
            regressionseries.add(float(x2),float(y2))
            regressioncollection.addSeries(regressionseries)

            print series.getKey(),":"
            print "  R:            %8.4f" % regression.getR()
            print "  R-squared:    %8.4f" % regression.getRSquare()
            print "  Significance: %8.4f" % regression.getSignificance()
            print
            
        plot.setDataset(1,regressioncollection)
        regressionRenderer = XYLineAndShapeRenderer(True,False)
        plot.setRenderer(1,regressionRenderer)
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
        
        colors = [0xec0000,0x58b911,0x6886ea,0xedd612,0xa93bb9,0xffb71b,0xe200df,0x1de2b6,0xdc91db,0x383838,0xb09344,0x4ea958,0xd78c9e,0x64008d,0xb0c95b]
        mainRenderer = plot.getRenderer(0)
        for i in range(collection.getSeriesCount()):
            try:
                mainRenderer.setSeriesPaint(i,Color(colors[i]))
                regressionRenderer.setSeriesPaint(i,Color(colors[i]))
            except IndexError: # Finite # of colors in the color array; beyond that let jfreechart pick
                break
        '''
        # Jump through some hoops to ensure regressions are same color as scatters for each series.
        # Initially: doesn't work because series are not indexed the same. And I don't see a way
        # to get the actual series from the renderer in order to compare names or something.
        mainRenderer = plot.getRenderer(0)
        print "Renderer is",type(mainRenderer)
        index = 0
        paint = mainRenderer.lookupSeriesPaint(index)
        print "Paint is",type(paint)
        while (paint is not None):
            print "Setting paint."
            regressionRenderer.setSeriesPaint(index,paint)
            index += 1
            paint = mainRenderer.getSeriesPaint(index)
        '''
        return plot