开发者

1-Dimensional Plots with Java

I've never used Java for graphics before so I am currently trying to learn.

As a basic exercise, I want to plot points contained in an array onto a number line but am not sure how to get started.

I am doing the following to draw the line:

public void drawNumberLine(Graphics g) {
    g.drawLine(0,0,100,0);
}

Not sure where to go from there since I don't know how I will be ab开发者_开发技巧le to plot the points on the line. I've read a few tutorials but all dealt with 2D plots so I was wondering if someone can direct me in the right direction.


What number range is your array? I'm assuming you want to scale it down to fit your 100 long line? Is it only positive numbers? In that case, something like this should work

//Find the max value for scaling purposes
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE
for(double i : array){
    if(i > max) max = i;
    if(i < min) min = i;
}


for(double i : array){
    //Replace 100 with a variable for how long the line is!
    double scaled = ((i-min)/(max-min)) * 100; 

    Ellipse.Double circle = new EllipseDouble(width, height, scaled, 0);

    g2d.draw(circle)
}

If it is an int array, make sure to avoid integer division.


Well, if you have a size of the base line, e.g. 100 pixels, and a start value, e.g. 0 pixels, you can calculate the exact pixel where to draw some marker for the point.

Example:

Line represents integers 10 to 20 and is drawn from 50 to 150 pixels:

x_offset = 50
lower_bound = 10
width = 100 pixels //(150 - 50)
range = 10 //(20 - 10)
pixels_per_step = width/range = 100/10 = 10

Thus, each integer marker i would be drawn at

x = x_offset + pixels_per_step * (i - lower_bound) => (replace constants)
x = 50 + 10 * (i - 10) => (example for i = 15)
x = 50 + 10 * (15 - 10) = 50 + 10 * 5 = 50 + 50 = 100 => draw marker 15 at 100 pixels

This should get you started. Note that you might have to round if pixels_per_step or iis not an integer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜