Search code examples
javapolar-coordinates

Connecting Polar Graph Coordinates


My program is a Polar graphing window. My issue is that when I graph r=a*sin(b*theta). My specific example shown below uses a=12 and b=8. When I connect the point drawn to the next I get something show below:

Polar Graph

The lines seem to be drawn across the petals, which looks wonderful, but is not correct. Below is the code drawing the points and lines:

for(int i=0; i< ptr.size(); i++){
        drawPoint(g2d, ptr.get(i), ptt.get(i));
        if(connectPoints && i!=ptr.size()-1){
            g.drawLine((int)(origin_x+Math.cos(ptt.get(i))*ptr.get(i)*ppp), 
                    (int)(origin_y-Math.sin(ptt.get(i))*ptr.get(i)*ppp), 
                    (int)(origin_x+Math.cos(ptt.get(i+1))*ptr.get(i+1)*ppp), 
                    (int)(origin_y-Math.sin(ptt.get(i+1))*ptr.get(i+1)*ppp));
        }
} 

ptr contains the r values and ptt contains the theta values. Here is the line adding the points:

for(double i=0; i<100; i+=0.1){
        pg.plot(12*Math.cos(8*i), i);
}

Why is this happening? How can it be fixed? Thanks ahead of time!


Solution

  • You're traversing the circle more than once and your sample points are not the same on each pass. That is why you are getting lines cutting across the petals. Try:

    double numberOfSteps = 1000;
    double stepSize = 2.0 * Math.PI / numberOfSteps; 
    for(double i=0; i<numberOfSteps; i++){
        double theta = i * stepsize;
        pg.plot(12*Math.cos(8.0 * theta), theta);
    }
    

    Experiment with numberOfSteps to fine tune.