Question

I'm currently trying to graph the equation r = 4 * sin(2 * theta) in the polar plane using matplotlib, based off of the linked example. Here's my code:

import numpy as np
import matplotlib.pyplot as plt
from math import sin, pi

def plot_polar(f, start=0, end=2*pi):
    theta = np.linspace(start, end, 1000)
    r = map(f, theta)

    ax = plt.subplot(111, polar=True)
    ax.plot(theta, r)
    ax.grid(True)

    plt.show()

plot_polar(lambda theta: 4 * sin(2 * theta))

This results in the following output:

incorrect

However, according to Wolfram Alpha, the correct graph looks like this:

correct

My code appears to be missing a good chunk of the graph -- it has only two petals, instead of four. I made sure to plot both equations as theta goes from 0 to 2pi, so they should be displaying the same thing.

Does anybody know what I'm doing wrong? I'm not sure if I'm just misunderstanding how to use matplotlib, or if I'm missing some obvious error.

Était-ce utile?

La solution

It looks like matplotlib is choking because you are giving it a negative as a radius.

I tried your code and got the same results. I changed your line

r = map(f, theta)

to be

r = map(abs(f), theta)

And got this plot:

radial plot

The "polar plot" from Wolfram is a little misleading if you ask me. It's certainly not structured like the matplotlib version.

Autres conseils

I ran the same exact code and got this. Maybe check your versions of numpy and matplotlib.

>>> import numpy as np
>>> np.version.version
'1.7.1'
>>> import matplotlib
>>> matplotlib.__version__
'1.1.1'

enter image description here

I think that there also is an issue with the trace of the polar function. It should trace the line in the (x pos, y pos) quadrant, then (xpos,yneg), to (xneg, yneg) and finally the (xneg, ypos) quadrant.

That is the concept behind these plots which led to understanding the travel of bodies in space. IF you fiddle the function to be r = sin(4*theta), you get the plot like the Wolfram plot.

Conceptually, there seems to be an issue plotting polar plots, even on a polar figure, and ending with cartesian co-ordinates. I suspect that the abs call on f sorts the problem but obscures that you are plotting the reversed r value, making this a discontinuous function, which it is not.

In terms of the movement of bodies relationship, it seems would be analogous to reversing gravity!!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top