Search code examples
pythonmatplotlibscientific-computing

Couple of matplotlib newbie doubts


I am just starting to use 'matplotlib' and I have hit upon 2 major roadblocks, which I can't seem to work around from the docs/examples,etc: Here is Python source:

#!/usr/bin/python
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
for i in range(0,301):

    print "Plotting",i

    # Reading a single column data file
    l=plt.plotfile("gen"+str(i))

    plt.xlabel('Population')
    plt.ylabel('Function Value')
    plt.title('Generation'+str(i))
    plt.axis([0,500,0,180])

    plt.plot()

    if len(str(i)) == 1:
        plt.savefig("../images/plot00"+str(i)+".png")
    if len(str(i)) == 2:
        plt.savefig("../images/plot0"+str(i)+".png")
    if len(str(i)) == 3:
        plt.savefig("../images/plot"+str(i)+".png")

    plt.clf()
  1. Doubt 1: As you can see, I am basically clearing the plot and then saving the new plot every time. I want to keep the range of the Y-axis constant and I am trying to do it via "plt.axis([0,500,0,180])". But it doesn;t seem to work and it is automatically set everytime.
  2. Doubt 2: Instead of obtaining the default plot in which the points are joined by continuous lines, I would prefer to obtain a plot of say, '*'. How would I do that?

Solution

    • As Tim Pietzcker points out, you can shorten if filename code at the end by using string number formatting.

      filename='plot%03d.png'%i
      

      replaces %03d with the integer i padded with up to 3 zero's. In Python2.6+, one can do the same thing with the less pretty but more powerful new string formatting syntax:

      filename='plot{0:03d}.png'.format(i)
      

    • To get the points plotted with stars, you can use the option marker='*'. And to get rid of the connecting lines, use linestyle='none'.
    • plt.plotfile(...) plots a figure. The call to plt.plot() plots a second figure overlaid on top of the first figure. The call to plt.plot() seems to modify the axis dimensions, wiping out the effect of plt.axis(...). Fortunately, the fix is simple: simply don't call plt.plot(). You don't need it.

    #!/usr/bin/env python
    import matplotlib
    import matplotlib.pyplot as plt
    
    matplotlib.use('Agg')   # This can also be set in ~/.matplotlib/matplotlibrc
    for i in range(0,3):
        print 'Plotting',i
        # Reading a single column data file
        plt.plotfile('gen%s'%i,linestyle='none', marker='*')
    
        plt.xlabel('Population')
        plt.ylabel('Function Value')
        plt.title('Generation%s'%i)
        plt.axis([0,500,0,180])
        # This (old-style string formatting) also works, especial for Python versions <2.6:
        # filename='plot%03d.png'%i
        filename='plot{0:03d}.png'.format(i)
        print(filename)
        plt.savefig(filename)
        # plt.clf()  # clear current figure