0

I used matplotlib.pyplot.contour to draw a line, but the result is strange.
My python code:

import numpy as np
from matplotlib import pyplot as plt

N = 1000

E = np.linspace(-5,0,N)
V = np.linspace(0, 70,N)
E, V = np.meshgrid(E, V)

L = np.sqrt(-E)
R = -np.sqrt(E+V)/np.tan(np.sqrt(E+V))

plt.contour(V, E,(L-R),levels=[0])
plt.show()

The result is:
enter image description here

But when I use Mathematica, the result is different.
Mathematica code is:

ContourPlot[Sqrt[-en] == -Sqrt[en + V]/Tan[Sqrt[en + V]], {V, 0, 70}, {en, -5, 0}]

The result is:

enter image description here

The result that I want is Mathematica's result.

Why does matplotlib.pyplot.contour give the wrong result? I am very confused!

It would be very appreciate if you can give me some idea! Thank you very much!

1
  • Have you tried not using the optional parameters for contour? Those could be causing these problems Commented Mar 19, 2019 at 15:46

1 Answer 1

1

The result given by matplotlib.pyplot.contour is numerically correct, but mathematically wrong.

Check what happens if you simply plot the tan(x):

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(0,2*np.pi,1000)
y = np.tan(x)

plt.plot(x,y)
plt.show()

enter image description here

You will get a line at the poles. This is because subsequent points are connected.

You can circumvent this by using np.inf for points larger than a certain number. E.g. adding

y[np.abs(y)> 200] = np.inf

would result in

enter image description here

The same approach can be used for the contour.

import numpy as np
from matplotlib import pyplot as plt

N = 1000

x = np.linspace(0, 70,N)
y = np.linspace(-5,0,N)
X,Y = np.meshgrid(x, y)

F = np.sqrt(-Y) + np.sqrt(Y+X)/np.tan(np.sqrt(Y+X))
F[np.abs(F) > 200] = np.inf

plt.contour(X, Y, F, levels=[0])
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.