unable to plot multiple lines with plot?

hi all,

i’m getting very strange behavior from the matplotlib ‘plot’ function when attempting to plot multiple lines. i have a series of x, y data points that are being generated in a loop and i want to simply plot each of them on the same plot. my code is:

import matplotlib
matplotlib.use(‘PDF’)
import matplotlib.pyplot as plt
from matplotlib import rc
rc(‘font’,{‘family’:‘sans-serif’,‘sans-serif’:[‘Helvetica’]})
plt.rcParams[‘ps.useafm’] = True
rc(‘font’,
{‘family’:‘sans-serif’,‘sans-serif’:[‘Helvetica’]})

my_fig = plt.figure(figsize=(6,5), dpi=100)
num_lines = 3

for n in range(0, num_lines):
print “Printing line %d” %(n+1)
x = range(0, 100)
y = (ones(100)*(n+1))
plt.plot(x, y)

plt.savefig(‘plot_example.pdf’)

when I do this, it only plots the last line (a horizontal line at y = 3). how can i get to actually plot all three lines?

more strangely, it shows stochastic behavior: sometimes when i run the code, it generates a green line at y = 3, and other times a blue line. from plot to plot, the upper bound of the y axis changes, sometimes being 3.15, sometimes 3.2. i’m not sure why it is doing that.

how can i get it to simply add whatever i plot in the body of the ‘for’ loop to the same graph? i tried adding plt.plot() after my call to plt.plot but that did not fix it.

thank you.

per freem wrote:

hi all,

i'm getting very strange behavior from the matplotlib 'plot' function when attempting to plot multiple lines. i have a series of x, y data points that are being generated in a loop and i want to simply plot each of them on the same plot. my code is:

import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rcParams['ps.useafm'] = True
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})

my_fig = plt.figure(figsize=(6,5), dpi=100)
num_lines = 3

for n in range(0, num_lines):
    print "Printing line %d" %(n+1)
    x = range(0, 100)
    y = (ones(100)*(n+1))
    plt.plot(x, y)

plt.savefig('plot_example.pdf')

when I do this, it only plots the last line (a horizontal line at y = 3). how can i get to actually plot all three lines?

more strangely, it shows *stochastic* behavior: sometimes when i run the code, it generates a green line at y = 3, and other times a blue line. from plot to plot, the upper bound of the y axis changes, sometimes being 3.15, sometimes 3.2. i'm not sure why it is doing that.

how can i get it to simply add whatever i plot in the body of the 'for' loop to the same graph? i tried adding plt.plot() after my call to plt.plot but that did not fix it.

thank you.

Per: The plots are there, you just can't see them because the y-axis has been auto-scaled so that the first and last lines lie on the top and bottom of the plot window. Just add plt.ylim(0,4) after the loop and you will see all three lines.

-Jeff