Juan Reséndiz
Juan Reséndiz

Reputation: 97

Problems while plotting on Matplotlib

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!!!

Upvotes: 2

Views: 2526

Answers (3)

unutbu
unutbu

Reputation: 879501

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

Upvotes: 3

BrenBarn
BrenBarn

Reputation: 251383

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)

Upvotes: 1

David Zwicker
David Zwicker

Reputation: 24278

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!

Upvotes: 0

Related Questions