Link to home
Start Free TrialLog in
Avatar of robin_at_mri
robin_at_mri

asked on

Inverting y-axis for drawing graph

Hey Experts,
Just wondering if there is a simple way you can change the y-coordinate system of the Java Graphics object so that a -ve value is drawn below the origin and a +ve value is drawn above.  i.e. if I draw a point at 30,-45 it is really being drawn at 30,45.  I am drawing a grid but my y-axis is inverted.  Short of negating every y-value in my drawGrid method, is there any other way to do this?
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You can. This move the origin to its usual position and y increases upwards:

public void paint(Graphics _g) {
     java.awt.Graphics2D g = (java.awt.Graphics2D)_g;
     // Move origin to 'normal' location, i.e. bottom left corner
     g.translate(0, getBounds().height);
     // Multiply y coordinates so that y increases 'normally', i.e. upwards
     g.scale(1.0, -1.0);
     // Red line
     g.setPaint(Color.red);
     // from origin to (40,40)
     g.drawLine(0,0,40,40);
}
Avatar of robin_at_mri
robin_at_mri

ASKER

So the problem wtih that approach is that it is mangling my axis labels.  a -10 is being printed upside down.  If I invert the scaling(again, to flip text right side up), the axis will be printed in the wrong position.
Then you need to restore the default transform to do 'normal' stuff. Save it at the beginning with

AffineTransform originalTransform = g.getTransform();

// Shift the axes then do your standard Cartesian stuff

g.setTransform(originalTransform);

// Now we're back in user/device space coordinates

// Do your labels

// Back to Cartesian if you want
It might be more convenient still to have two transforms - the default, and your 'normal axes' one, then you can just switch between them.

But if I switch to a normal transformation won't my 20 label for 20 units in the y-axis be drawn in the -20 position?


Rob
Not if you call it with the default (identity) transformation.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry that it took so long to award the points!!!

Rob
;-)