5

I am trying to plot the following !

from numpy import *
from pylab import *
import random

for x in range(1,500):
    y = random.randint(1,25000)
    print(x,y)   
    plot(x,y)

show()

However, I keep getting a blank graph (?). Just to make sure that the program logic is correct I added the code print(x,y), just the confirm that (x,y) pairs are being generated.

(x,y) pairs are being generated, but there is no plot, I keep getting a blank graph.

Any help ?

3
  • Arkapravo, i have no problem w/ the accepted answer; i just wanted to mention that this five-line template: from matplotlib import pyplot as PLT; fig=PLT.figure(); ax1=fig.add_subplot(111); ax1.plot(x, y); PLT.show(), is a quick way to get a working x-y plot 98% of the time. ('x', 'y' are lists or 1D Numpy arrays, btw). Commented Apr 7, 2010 at 8:19
  • 1
    @doug: you can go the same thing in a simpler way: from matplotlib import pyplot at plt; plt.plot(x, y); plt.show(). Commented Apr 7, 2010 at 9:20
  • @doug: Thanks ! ... I accepted Daniel G's answer since it immediately solved all my issues ! .... :) .. too bad 2 answers cannot be chosen ! Commented Apr 7, 2010 at 10:30

1 Answer 1

5

First of all, I have sometimes had better success by doing

from matplotlib import pyplot

instead of using pylab, although this shouldn't make a difference in this case.

I think your actual issue might be that points are being plotted but aren't visible. It may work better to plot all points at once by using a list:

xPoints = []
yPoints = []
for x in range(1,500):
    y = random.randint(1,25000)
    xPoints.append(x)
    yPoints.append(y)
pyplot.plot(xPoints, yPoints)
pyplot.show()

To make this even neater, you can use generator expressions:

xPoints = range(1,500)
yPoints = [random.randint(1,25000) for _ in range(1,500)]
pyplot.plot(xPoints, yPoints)
pyplot.show()
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for 'import pyplot'--obviously for those former Matlab users, pylab is a massive convenience, but the almost interchangeable use of these two dialects in the docs, examples, etc. made Matplotlib, brilliant as it is, much harder for me to learn.
Many thanks dudes ! I guess I had last dabbled with matplotlib, sometimes in October 2009 , certain needs came up that I had to come back to it in April 2010 .
yPoints = list(map(lambda: random.randint(1,25000), xPoints)) and no need to keep track of an extra variable.

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.