TheRealFakeNews
TheRealFakeNews

Reputation: 8143

Getting matplotlib to work - plots not showing

I was able to successfully install matplotlib; however, when I run my code, I don't get an error, but instead the Python icon bouncing over and over again.

Python

I don't know if it has anything to do with

from rcParamsSettings import *

I don't have any idea what that is, but if I try to run it with that line uncommented out, I get

ImportError: No module named rcParamsSettings

Here's the code I'm trying to run:

import pylab
#from rcParamsSettings import *
import random

def flipPlot(minExp, maxExp):
    """Assumes minExp and maxExp positive integers; minExp < maxExp
       Plots results of 2**minExp to 2**maxExp coin flips"""
    ratios = []
    diffs = []
    xAxis = []
    for exp in range(minExp, maxExp + 1):
        xAxis.append(2**exp)
    for numFlips in xAxis:
        numHeads = 0
        for n in range(numFlips):
            if random.random() < 0.5:
                numHeads += 1
        numTails = numFlips - numHeads
        ratios.append(numHeads/float(numTails))
        diffs.append(abs(numHeads - numTails))
    pylab.title('Difference Between Heads and Tails')
    pylab.xlabel('Number of Flips')
    pylab.ylabel('Abs(#Heads - #Tails)')
    pylab.plot(xAxis, diffs)
    pylab.figure()
    pylab.title('Heads/Tails Ratios')
    pylab.xlabel('Number of Flips')
    pylab.ylabel('#Heads/#Tails')
    pylab.plot(xAxis, ratios)

random.seed(0)
flipPlot(4, 20)

What do I need to do to get the code running?

Note: My experience with programming and Python is very limited; I'm just starting out.

Upvotes: 1

Views: 84

Answers (2)

NDevox
NDevox

Reputation: 4086

You need to use pylab.show() otherwise nothing will come up.

See the example here: http://matplotlib.org/examples/pylab_examples/simple_plot.html

(although you should avoid using from pylab import *, the way you import is fine.)

There are cases in MatPlotLib where you do not want to show the graph. An example I have is designing a graph on a server using data collected by an automated process. The server has no screen and is only accessed by a terminal, and therefore trying to show a graph will result in an error as there is no DISPLAY variable set (there is no screen to display to).

In this case it would be normal to save the figure somewhere using pylab.savefig(), and then maybe email it or use an ftp to send it somewhere it can be viewed.

Because of this MatPlotLib will not implicitly show a graph and must be asked to show it.

Upvotes: 1

Tim
Tim

Reputation: 83

Your code works for me if I add a pylab.show().

Alternatively, you could save the plot to a file:

pylab.savefig("file.png")

This makes sense if you are updating your plot frequently.

Upvotes: 1

Related Questions