Title: Graphing
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Graphing Examples

AGraph3.java


//  The basic parameters taken by this applet are as follows:
//
//  points            this contains the number of points in the Graph
//  title              Some String
// P<num>              Data for each of the Lines to be graphed.


import java.awt.*;

public class AGraph3 extends java.applet.Applet {

    static final int    GRAPH_SPACING = 15;
    static final int    SCALING= 4;

    String              title;
    Font                titleFont;
    FontMetrics         titleFontMetrics;
    int                 points;
    int                 values2[];


    public void start()
    {
    }

    public  void init()
    {
        String rs, rs2;
        Float F;
        String default_color="green";

        System.out.println("Window Size H= " + getBounds().height +
             " W = " + getBounds().width);

        titleFont = new java.awt.Font("Courier", Font.BOLD, 20);
        titleFontMetrics = getFontMetrics(titleFont);

// Read in the parameters from the Html file

        title = getParameter("title");
        if (title == null)
        {
            title = "Graph";
        }
        System.out.println("Title = " + title);

        rs = getParameter("points");
        if (rs == null)
        {
            points = 5;
        }
        else
        {
            points = Integer.parseInt(rs);
        }
        System.out.println("points = " + points);


//  Allocate Memory space for the point data
        values2  = new int[points];



// Read in the point data and all of the possible specifications for
// each point

        for (int i=0; i < points; i++)
            {
            // parse the value for this point

            values2[i] = -1;


            rs = getParameter("P" + i);
            System.out.println("P"+i + " = " + rs);
            if (rs != null)
            {
                  try
                        {
                        values2[i] = Integer.parseInt(rs);
                        }
                  catch (NumberFormatException e)
                       {
                        values2[i] = -1;
                        }

                } //End of the For loop on j


        }  // end of for loop on i

    }//End of init


    public  void paint(Graphics g) {
        int width, i, j, xOffset = 0;
        int cx, cy, cloc, yOffset=0, TitleOffset;


        // draw the title centered at the bottom of the bar graph
        g.setColor(Color.black);
        width = titleFontMetrics.stringWidth(title);
        g.setFont(titleFont);
        TitleOffset = 25;
        g.drawString(title,
             Math.max((getBounds().width - width)/2, 0),
             TitleOffset);


        xOffset = 10;
        yOffset = TitleOffset +  titleFont.getSize() ;


// Draw the Top Line
        g.drawLine(xOffset, yOffset, getBounds().width, yOffset);
// Draw the Left Side Line
        g.drawLine(xOffset, yOffset, xOffset, getBounds().height);
        yOffset +=  10;


        g.setColor(Color.black);
        System.out.println("xOffset= " + xOffset + " yOffset = " + yOffset);


    // Plot the Graph Lines


            int lastx=0, lasty=0;


             for (i=0; i < points; i++)
                {
                if (values2[i] < 0)
                  {
                     System.out.println("Bad data for i,j = " + i);
                     break;
                  }

                // set the Y coordinate
                cy = GRAPH_SPACING * i + yOffset;

                // set the X coordinate to be the getBounds().width of the widest
                // label
                cx = xOffset + (int)(SCALING * values2[i]);

                // After the first point we draw lines.
                if (i > 0)
                         g.drawLine(lastx, lasty, cx, cy);

                lastx=cx;
                lasty=cy;

             }//End of For loop on i



   }//End of paint
}//End of Applet







AGraph2.java


//  The basic parameters taken by this applet are as follows:
//
//  points            this contains the number of points in the Graph
//  lines             contains the number Lines to Graph

//  title              Some String
// L<num>_color        Color of the <num> line where <num> > 0
//                     and <num> < lines
// L<num_lname         Name to be associated with the Graph Line
// P<num>              Data for each of the Lines to be graphed.




import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;


public class AGraph2 extends java.applet.Applet {

    static final int    GRAPH_SPACING = 15;
    static final int    SCALING= 4;

    String              title;
    Font                titleFont;
    FontMetrics         titleFontMetrics;
    Font                labelFont;
    FontMetrics         labelFontMetrics;
    int                 points;
    int                 lines;
    int                 values2[][];
    Object              colors[];
    Object              lineNames[];



    public synchronized void start()
    {
    }

    public synchronized void init()
    {
        String rs, rs2;
        Float F;
        String default_color="green";

        System.out.println("Window Size H= " + getBounds().height +
             " W = " + getBounds().width);

        titleFont = new java.awt.Font("Courier", Font.BOLD, 20);
        titleFontMetrics = getFontMetrics(titleFont);
        labelFont = new java.awt.Font("Courier", Font.BOLD, 12);
        labelFontMetrics = getFontMetrics(labelFont);

// Read in the parameters from the Html file

        title = getParameter("title");
        if (title == null)
        {
            title = "Graph";
        }

        rs = getParameter("points");
        if (rs == null)
        {
            points = 5;
        }
        else
        {
            points = Integer.parseInt(rs);
        }
       System.out.println("points = " + points);


        rs = getParameter("lines");
        if (rs == null)
        {
            lines = 2;
        }
        else
        {
            lines = Integer.parseInt(rs);
        }
       System.out.println("lines = " + lines);



//  Allocate Memory space for the point data
        values2  = new int[points][lines];

        colors = new Color[lines];
        lineNames = new String[lines];

// Read in the point data and all of the possible specifications for
// each point

        for (int i=0; i < points; i++)
            {
            // parse the value for this point

           for(int j=0; j < lines; j++)
            values2[i][j] = -1;


            rs = getParameter("P" + i);
            if (rs != null)
            {
               for (int j= 0; j < lines; j++)
              {
                  int index = rs.indexOf(",");

                    if (index <= 0)
                        break;
                    rs2 = rs.substring(0,index);
                    rs = rs.substring(index+1);

                  try
                        {
                        values2[i][j] = Integer.parseInt(rs2);
                        }
                  catch (NumberFormatException e)
                       {
                        values2[i][j] = -1;
                        }

          System.out.println("i,j, value2 = " + i + ", " + j +", " + values2[i][j]);



                     }
                } //End of the For loop on j


        }  // end of for loop on i



      // Get the colors and Point Labels
        for (int i=0; i < lines; i++)
        {

            // parse the label for this point
            rs = getParameter("L" + i + "_lname");
            lineNames[i] = (rs == null) ? "" : rs;


            // parse the color attribute for this point
            rs = getParameter("L" + i + "_color");
            if (rs == null) {
                rs = default_color;
                }

                if (rs.equals("red")) {
                    colors[i] = Color.red;
                } else if (rs.equals("green")) {
                    colors[i] = Color.green;
                } else if (rs.equals("blue")) {
                    colors[i] = Color.blue;
                } else if (rs.equals("pink")) {
                    colors[i] = Color.pink;
                } else if (rs.equals("orange")) {
                    colors[i] = Color.orange;
                } else if (rs.equals("magenta")) {
                    colors[i] = Color.magenta;
                } else if (rs.equals("cyan")) {
                    colors[i] = Color.cyan;
                } else if (rs.equals("white")) {
                    colors[i] = Color.white;
                } else if (rs.equals("yellow")) {
                    colors[i] = Color.yellow;
                } else if (rs.equals("gray")) {
                    colors[i] = Color.gray;
                } else if (rs.equals("darkGray")) {
                    colors[i] = Color.darkGray;
                } else if (rs.equals("lightGray")) {
                    colors[i] = Color.lightGray;
                } else if (rs.equals("black")) {
                    colors[i] = Color.black;
                } else {
                    colors[i] = Color.yellow;
                }

        } //End of For Loop


    }//End of init


    public synchronized void paint(Graphics g) {
        int i, j, xOffset = 0;
        int cx, cy, cloc, yOffset=0, TitleOffset;
        int ylegend;


        // draw the title centered at the bottom of the bar graph
        g.setColor(Color.black);
        i = titleFontMetrics.stringWidth(title);
        g.setFont(titleFont);
        TitleOffset = 25 ;
        g.drawString(title, Math.max((getBounds().width - i)/2, 0), TitleOffset);

        g.setFont(labelFont);

        xOffset = 10;
        ylegend = TitleOffset +  labelFont.getSize() + 10;
        yOffset = ylegend + 30;

        yOffset += 5;

// Draw the Top Line
        g.drawLine(xOffset, yOffset, getBounds().width, yOffset);
// Draw the Left Side Line
        g.drawLine(xOffset, yOffset, xOffset, getBounds().height);
        yOffset +=  10;


        g.setColor(Color.black);
        g.setFont(labelFont);
      yOffset += 10; // A little space
      System.out.println("xOffset= " + xOffset + " yOffset = " + yOffset);


    // Build the Legend Line

     g.setColor(Color.black);
       g.drawString((String)"Legend:  " , xOffset ,
                            ylegend + labelFontMetrics.getAscent());
       cx = xOffset + labelFontMetrics.stringWidth((String)"Legend:  "  ) ;
       for (j=0 ; (j < lines) ; j++)
           {
               g.setColor((Color)(colors[j]));


               g.drawString((String)lineNames[j], cx ,
                            ylegend + labelFontMetrics.getAscent());
               cx += labelFontMetrics.stringWidth((String)(lineNames[j]))+ 10 ;
            }//End of For loop on j


    // Plot the Graph Lines

        for (j=0; j < lines; j++)
        {
            int lastx=0, lasty=0;
            // draw the line in the current color
             g.setColor((Color)(colors[j]));

             for (i=0; i < points; i++)
                {
                if (values2[i][j] < 0)
                  {
                  System.out.println("Bad data for i,j = " + i+ ", "+j);
                break;
                  }

                // set the Y coordinate
                cy = GRAPH_SPACING * i + yOffset;

                // set the X coordinate to be the getBounds().width of the widest
                // label
                cx = xOffset + (int)(SCALING * values2[i][j]);

                // After the first point we draw lines.
                if (i > 0)
                         g.drawLine(lastx, lasty, cx, cy);

                lastx=cx;
                lasty=cy;

             }//End of For loop on i
        }//End of For loop on j


   }//End of paint
}//End of Applet


AGraph.java


//  The basic parameters taken by this applet are as follows:
//
//  points            this contains the number of points in the Graph
//  lines             contains the number Lines to Graph

//  title              Some String
// L<num>_color        Color of the <num> line where <num> > 0
//                     and <num> < lines
// L<num_lname         Name to be associated with the Graph Line
// P<num>_label        Left Hand label for the Plotted Points
// P<num>              Data for each of the Lines to be graphed.




import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;

public class AGraph extends java.applet.Applet {

    static final int    MAX_DISPLAY_SCALES = 50;

    String              title;
    Font                titleFont;
    FontMetrics         titleFontMetrics;
    Font                labelFont;
    FontMetrics         labelFontMetrics;
    int                 points;
    int                 lines;
    int                 values2[][];
    Object              colors[];
    Object              labels[];
    Object              lineNames[];
    int                 display_scale_values[];
    int                 display_scale_num = 0;
    int                 maxScaleWidth =0;
    int                 maxLabelWidth = 0;
    int                 dataWidth;
    int                 dataSpacing = 10;
    int                 max = 1;
    int                 AddNumbers=0;
    int                 SkewGraphs=3;
    float               scale=10;

    static final int    LAST_TEST = 100000000;

 //---------------------------------------------
// Ignore the following routine if you aren't interested
// the scaling technique used by this Applet
//----------------------------------------------
    protected void computeDisplayScales(int max)
    {
        int numIntervals, intervalSize;
        String rs;

    // We would like a scale mark about every 100 pixels, so
      // numIntervals is an estimate of the number of scale labels
      // we would like

      numIntervals = (getBounds().width - 30)/100;

    // Candidate Interval spacing

        int testSizes[] = {1, 2, 4, 5, 8, 10, 15, 20, 25, 30, 50, 75,
                                100, 150, 200, 300, 400, 500,
                                1000,2000, 3000, 4000, 5000, 8000,
                                10000,20000,40000, 50000, 80000,
                                100000, 200000, 400000, 500000, 800000,
                                1000000, 2000000,4000000, 5000000, 8000000,
                                10000000, 20000000, 40000000, 50000000, 80000000,
                                LAST_TEST};

      // We would like an interval spacing that gives us roughly
      // numIntervals on this Chart.

        intervalSize = LAST_TEST;
        for (int i=0; testSizes[i] != LAST_TEST; i++)
            {
            if (numIntervals * testSizes[i+1] > max)
               {
               // With this interval size we get roughly
               //numIntervals on this chart.
               intervalSize = testSizes[i];
               break;
                }
             }
        System.out.println("numIntervals= " + numIntervals + " intervalSize = " + intervalSize);


        // Now that we know the intervalSize, we can figure out
        // what the scale labels should be.

        for (int i=0; i < MAX_DISPLAY_SCALES; i++)
        {
          display_scale_values[i] = (i+1) * intervalSize;
          if (display_scale_values[i] > max)
            {   // bail out so that scale labels never exceed
                // largest data value
                break;
            }
          rs = "" + display_scale_values[i];
          maxScaleWidth = Math.max(
                         labelFontMetrics.stringWidth((String)(rs)),
                         maxScaleWidth);

          display_scale_num = i+1;
        }
    }


    public synchronized void start()
    {
    }

    public synchronized void init()
    {
        String rs, rs2;
        Float F;
        String default_color="green";

        System.out.println("Window Size H= " + getBounds().height +
             " W = " + getBounds().width);

        titleFont = new java.awt.Font("Courier", Font.BOLD, 20);
        titleFontMetrics = getFontMetrics(titleFont);
        labelFont = new java.awt.Font("Courier", Font.BOLD, 12);
        labelFontMetrics = getFontMetrics(labelFont);

// Read in the parameters from the Html file

        title = getParameter("title");
        if (title == null)
        {
            title = "Chart";
        }

        rs = getParameter("points");
        if (rs == null)
        {
            points = 5;
        }
        else
        {
            points = Integer.parseInt(rs);
        }
     System.out.println("points = " + points);


        rs = getParameter("lines");
        if (rs == null)
        {
            lines = 2;
        }
        else
        {
            lines = Integer.parseInt(rs);
        }
     System.out.println("lines = " + lines);



//  Allocate Memory space for the point data
        values2  = new int[points][lines];

        display_scale_values = new int[MAX_DISPLAY_SCALES];
        colors = new Color[lines];
        labels = new String[points];
        lineNames = new String[lines];

// Read in the point data and all of the possible specifications for
// each point

        for (int i=0; i < points; i++)
            {
            // parse the value for this point

           for(int j=0; j < lines; j++)
            values2[i][j] = -1;


            rs = getParameter("P" + i);
            if (rs != null)
            {
               for (int j= 0; j < lines; j++)
              {
                  int index = rs.indexOf(",");

                    if (index <= 0)
                        break;
                  rs2 = rs.substring(0,index);
                    rs = rs.substring(index+1);

                  try
                {
                        values2[i][j] = Integer.parseInt(rs2);
                        }
              catch (NumberFormatException e)
                {
                        values2[i][j] = -1;
                        }

  //        System.out.println("i,j, value2 = " + i + ", " + j +", " + values2[i][j]);

                   // We want to remember the largest value to help us scale
                   // the Graph to fit in the allocated space.
                   if (values2[i][j] > max)
                      {
                           max = values2[i][j];
                       }


                     }
                } //End of the For loop on j

            // parse the label for this point
            rs = getParameter("P" + i + "_label");
            labels[i] = (rs == null) ? "" : rs;

// We want to remember the largest label width to know how to
// allocate space for the Graph
            maxLabelWidth = Math.max(
                 labelFontMetrics.stringWidth((String)(labels[i])),maxLabelWidth);
        }  // end of for loop on i



        dataWidth = labelFont.getSize();


         scale = (float)(getBounds().width - 100 - maxLabelWidth) /(float)max;

         System.out.println("MaxLabelWidth = " + maxLabelWidth);
         System.out.println("Scale Computed = " + scale);

         // Now that we know all about the data, we can compute the
         // data scales appropriate.
         computeDisplayScales(max);




      // Get the colors and Point Labels
        for (int i=0; i < lines; i++)
        {

            // parse the label for this point
            rs = getParameter("L" + i + "_lname");
            lineNames[i] = (rs == null) ? "" : rs;


            // parse the color attribute for this point
            rs = getParameter("L" + i + "_color");
            if (rs == null) {
                rs = default_color;
                }

                if (rs.equals("red")) {
                    colors[i] = Color.red;
                } else if (rs.equals("green")) {
                    colors[i] = Color.green;
                } else if (rs.equals("blue")) {
                    colors[i] = Color.blue;
                } else if (rs.equals("pink")) {
                    colors[i] = Color.pink;
                } else if (rs.equals("orange")) {
                    colors[i] = Color.orange;
                } else if (rs.equals("magenta")) {
                    colors[i] = Color.magenta;
                } else if (rs.equals("cyan")) {
                    colors[i] = Color.cyan;
                } else if (rs.equals("white")) {
                    colors[i] = Color.white;
                } else if (rs.equals("yellow")) {
                    colors[i] = Color.yellow;
                } else if (rs.equals("gray")) {
                    colors[i] = Color.gray;
                } else if (rs.equals("darkGray")) {
                    colors[i] = Color.darkGray;
                } else if (rs.equals("lightGray")) {
                    colors[i] = Color.lightGray;
                } else if (rs.equals("black")) {
                    colors[i] = Color.black;
                } else {
                    colors[i] = Color.yellow;
                }

        } //End of For Loop


    }//End of init


    public synchronized void paint(Graphics g) {
        int i, j, xOffset = 0;
        int cx, cy, cloc, yOffset=0, TitleOffset;
        int ylegend;
        char l[] = new char[1];
        String rs;
        int    ArrowLen   = 15;


        // draw the title centered at the bottom of the bar graph
        g.setColor(Color.black);
        i = titleFontMetrics.stringWidth(title);
        g.setFont(titleFont);
        TitleOffset = 25 ;
        g.drawString(title, Math.max((getBounds().width - i)/2, 0), TitleOffset);

        g.setFont(labelFont);

        xOffset = maxLabelWidth + 10;
        ylegend = TitleOffset +  labelFont.getSize() + 10;
        yOffset = ylegend + 30;
        if (display_scale_num > 0)
                {
                for (i=0; i < display_scale_num; i++)
                        {
                        cloc = xOffset + (int)((display_scale_values[i] *scale))  ;
                        if (display_scale_values[i] < 10000)
                            rs = "" + display_scale_values[i];
                        else if (display_scale_values[i] < 10000000)
                            rs = "" + (display_scale_values[i]/1000) + "K";
                        else
                            rs = "" + (display_scale_values[i]/1000000) + "M";
                        g.drawString(rs, cloc-10,  yOffset);
                        g.drawLine(cloc, yOffset+5,cloc, yOffset+10);
                        }
                yOffset += 5;

                g.drawLine(xOffset, yOffset,
                        xOffset +  (int)(scale*display_scale_values[display_scale_num-1]),
                        yOffset);
                g.drawLine(xOffset, yOffset, xOffset, getBounds().height);
                yOffset +=  10;
                }

        g.setColor(Color.black);
        g.setFont(labelFont);
      yOffset += dataSpacing;
      System.out.println("xOffset= " + xOffset + " yOffset = " + yOffset);

        for (i=0; i < points; i++)
                {
                // set the Y coordinate
                cy = ((dataWidth + dataSpacing) * i) +  yOffset;

                // draw the labels

                g.drawString((String)labels[i], 0,
                             cy + labelFontMetrics.getAscent());

        }//End of For loop

    // Build the Legend Line

     g.setColor(Color.black);
       g.drawString((String)"Legend:  " , xOffset ,
                            ylegend + labelFontMetrics.getAscent());
       cx = xOffset + labelFontMetrics.stringWidth((String)"Legend:  "  ) ;
       for (j=0 ; (j < lines) ; j++)
           {
               g.setColor((Color)(colors[j]));


               g.drawString((String)lineNames[j], cx ,
                            ylegend + labelFontMetrics.getAscent());
               cx += labelFontMetrics.stringWidth((String)(lineNames[j]))+ 10 ;
            }//End of For loop on j


    // Plot the Graph Lines

        for (j=0; j < lines; j++)
        {
            int lastx=0, lasty=0;
            // draw the line in the current color
             g.setColor((Color)(colors[j]));

             for (i=0; i < points; i++)
                {
                if (values2[i][j] < 0)
                  {
                  System.out.println("Bad data for i,j = " + i+ ", "+j);
                break;
                  }

                // set the Y coordinate
                cy = ((dataWidth + dataSpacing) * i) + dataWidth/2 + yOffset;

                // set the X coordinate to be the getBounds().width of the widest
                // label
                cx = xOffset + (int)(scale * values2[i][j]);


                if (i > 0)
            g.drawLine(lastx, lasty, cx, cy);

                lastx=cx;
                lasty=cy;

             }//End of For loop on i
        }//End of For loop on j


   }//End of paint
}//End of Applet