2

I'm having a problem using python matplotlib while creating a basic plot of a function, in wolfram alpha and other plotting engines the final plot seems to be so different from the one I'm creating via matplotlib.

I followed the example inside matplotlib and I just replaced the np.sin(x) function for the function I need to plot.

I'm using several functions so this is the first one I need to plot but it's not working at all.

Here's the code I'm using and the plot comparison just ahead.

__author__ = 'alberto'
#
import numpy 
import matplotlib.pyplot as plt
#
x = numpy.arange(-20, 20, 0.1)
y = ((3*x**2) + 12/(x**3) - 5)
plt.plot(x, y)
plt.show()

Wolfram

Function plotted by wolfram

Matplotlib.

Function plotted by matplotlib

I'm using Anaconda Python(2.7.8).

Have a nice day!!!

3 Answers 3

3

You can make one call to plt.plot generate two disconnected curves (thus handling asymptotes) by assigning nan to extreme values. Mathematica handles this for you automatically; matplotlib requires you to do a little work:

import numpy  as np
import matplotlib.pyplot as plt

x = np.linspace(-20, 20, 1000)
y = ((3*x**2) + 12/(x**3) - 5)
mask = np.abs(y) > 100
y[mask] = np.nan
plt.plot(x, y)
plt.grid()
plt.show()

yields

enter image description here

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

1 Comment

Thanks you all for your answers! Finally I got what I was doing, Thanks a lot! I was smashing my head into the keyboard X__X
1

If you look at the axis labels, you can see that matplotlib is showing you a much larger viewing window than Wolfram Alpha. Wolfram alpha is showing you roughly -4 <= x <= 4 and -50 <= y <= 100, but matplotlib is showing you -20 <= x <= 20 and y limits that are gigantic.

To get a comparable graph, set the view limits:

plt.xlim(-4, 4)
plt.ylim(-50, 100)

Comments

0

You have to restrict the vertical dimension manually! Here is a possible solution:

import numpy 
import matplotlib.pyplot as plt

x = numpy.arange(-20, 20, 0.1)
y = ((3*x**2) + 12/(x**3) - 5)
plt.plot(x, y)
plt.ylim(-50, 100)
plt.show()

Note the plt.ylim function!

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.