# Graph from array of numbers

Printable View

• 05-07-2003, 10:22 PM
vanuatu
Graph from array of numbers
Does any one know how to create a bar and line graph separately from any array of numbers?

For example int test[] ={0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,300};

To be simple I was trying to draw a bar graph by using
g.drawRect(0, 10, 2, 0);
g.drawRect(20, 20, 2, 20);
g.drawRect(40, 30, 2, 40);

This draws the bars out of rectangle, but they are not leveled.

I tried making each of the Ys the same:

g.drawRect(0, 10, 2, 0);
g.drawRect(20, 10, 2, 20);
g.drawRect(40, 10, 2, 40);

This resulted in the bars (rectangles) being on the same line but appearing to be upside down.

As far as quadrants in geometry, it looks as though I'm drawing to the wrong one.
• 05-08-2003, 02:14 AM
sharbov
drawLine
Assuming your x coordinate is 1..n
You can do:

while(i < test.lengh)
{
g.drawLine(i,test[i],i+1,test[i+1]);
}

That will draw the whole array.
• 05-08-2003, 08:17 PM
vanuatu
Thanks..

Any idea about the bar graph?

The following is what I have, and it puts the bars upside down. How can I get the bars right side up?

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.Graphics;

public class testergraph2 extends Applet
{

double f(double x) {
return ( ( Math.sin(x/5) + 2) * getSize().height / 4) ;
}
//int test[] = {0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,300};
int test[] = {0,100,20,30,400,50,60,70,80,90,100,110,120,130,140,150,160,300};
int startingPoint = 0;
int coordX, coordY, coordX2, coordY2;
//int i = 1;
int x = 0;
int constant = 10;
int width = 2;

int i = 1;
int j = 0;

int hold = 0;
int sizeofarray = test.length - 1;
//Color color;

public void init()
{
resize(300 , 300);
}

public void paint(Graphics g)
{

int i = 0;
System.out.println(sizeofarray);
for(int pass=0; pass < sizeofarray; pass++)
{
for(int t=0; t < sizeofarray; t++)
{
if(test[t] > test[t+1])
{
hold=test[t];
test[t] = test[t+1];
test[t+1] = hold;
}
}
}

g.fillRect(x, (int)f(constant), width,i);
while(i != test.length)
{

g.fillRect(test[i],(int)f(constant),width,i);

i++;
}

}

static boolean inApplet = true;
public static void main(String args[])
{
inApplet = false;
// Create the frame this applet will run in
Frame appFrame = new Frame("Bar Graph");

// Create an instance of the applet
testergraph2 myApp = new testergraph2();

// Add the current application to the frame
appFrame.add("Center", myApp);

// The frame needs a layout manager
myApp.setLayout(new FlowLayout());

// Add the applet to the frame
appFrame.add(myApp);

// Have to give the frame a size before it is visible
appFrame.resize(400, 300);

// Make the frame appear on the screen
appFrame.show();

}

}