John_dydx
John_dydx

Reputation: 961

plot function in python

I'm a complete newbie to python (this is my first post) but I have some experience programming in R. I've been going through the Crash Course in Python for Scientists tutorial.

I got as far as the matplotlib bit-I havent been able to go beyond this as the plot function is not recognized despite importing matplotlib. I'm using the idle in python 2.7.3 (I'm using a mac).

Here's what I'm trying to do:

>>> import matplotlib
>>> plot(range(20))

Here's the error message: # error message

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
plot(range(20))
NameError: name 'plot' is not defined

Can anyone help out at all? I know there are loads of other editors I could use but I prefer something similar to the R console where I can just type directly into the command line. I still haven't figured out a short cut for running a code directly from the idle editor-my f5 key is for something else and it doesn't run when I type it.

Upvotes: 0

Views: 3336

Answers (3)

tmdavison
tmdavison

Reputation: 69116

plot is a function of matplotlib.pyplot, so:

import matplotlib.pyplot as plt

plt.plot(range(20))

EDIT:

To see the plot, you will normally need to call

plt.show()

to display the figure, or

plt.savefig('figname.png')

to save the figure to a file after calling plt.plot().

As @JRichardSnape pointed out in the comments, import matplotlib.pyplot as plt is now a widely used convention, and is often implied around this site. The beginners guide has some useful information on this.

Upvotes: 3

chicao
chicao

Reputation: 86

You have to import the pyplot module of matplotlib and call the plot function.

import matplotlib.pyplot as plt

This plt is an alias for matplotlib.pyplot, so when plotting your range of values, just use the defined alias:

plt.plot(range(20))

I usually need to show my plots to colleages, so I save them in a figure instead of showing directly:

plt.savefig('output_image.png', dpi=300)

But if you need only a brief look in the output, just show your plot:

plt.show()

Upvotes: 3

bakkal
bakkal

Reputation: 55448

I prefer something similar to the R console where I can just type directly into the command line.

matplotlib is a plotting library, far from being the environment you seem to be seeking

If you want an environment similar to R, you probably will want to use pylab along with matplotlib

from pylab import *
plot(...)
show()

e.g. http://matplotlib.org/examples/pylab_examples/simple_plot.html

Also consider using ipython instead of the stock IDLE/Python prompt, highly recommended for data science, http://matplotlib.org/users/shell.html#ipython-to-the-rescue

That gives a much better environment, notice the %pylab command to trigger that mode, or try ipython --pylab to launch it

If you're used to doing literate programming in R, I recommend learning IPython notebooks, http://ipython.org/notebook.html

Upvotes: 2

Related Questions