24

My code is as follows, the problem is instead of having one plot, I get 242 plots. I tried putting the plt.show() outside the loop, it didn't work.

import numpy as np
import matplotlib.pyplot as plt
import csv

names = list()

with open('selected.csv','rb') as infile:
    reader = csv.reader(infile, delimiter = ' ')
    for row in reader:
        names.append(row[0])

names.pop(0)

for j in range(len(names)):
    filename = '/home/mh/Masters_Project/Sigma/%s.dat' %(names[j])
    average, sigma = np.loadtxt(filename, usecols = (0,1), unpack = True, delimiter = ' ')
    name = '%s' %(names[j]) 
    plt.figure()
    plt.xlabel('Magnitude(average)', fontsize = 16)
    plt.ylabel('$\sigma$', fontsize = 16)
    plt.plot(average, sigma, marker = '+', linestyle = '', label = name)
plt.legend(loc = 'best')
plt.show()
2
  • you should not use for i in range(len(xs)) and xs[i] to iterate over elements of an array. Use for x in xs:. Another Point: Why do you use such a complicated way for reading in the names? names = np.genfromtxt("selected.csv", delimiter=" ", dtype=np.str, skiprows=1) Commented Oct 14, 2014 at 16:00
  • Thanks very much. Usually I don't work with csv files, but your way is a short and neat way of doing. Commented Oct 15, 2014 at 9:08

2 Answers 2

28

Your issue is that you're creating a new figure with every iteration using plt.figure(). Remove this line from your for loop and it should work fine, as this short example below shows.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

for a in [1.0, 2.0, 3.0]:
    plt.plot(x, a*x)

plt.show()

Example plot

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, noted.Is there a way of avoiding for loops?
@MichaelHlabathe that is a different question entirely to the one you've asked. I would suggest you ask a new question in this case, rather than me editing my answer to answer something different.
4

Let me improve your code a bit:

import numpy as np
import matplotlib.pyplot as plt

# set the font size globally to get the ticklabels big too:
plt.rcParams["font.size"] = 16

# use numpy to read in the names
names = np.genfromtxt("selected.csv", delimiter=" ", dtype=np.str, skiprows=1)

# not necessary butyou might want to add options to the figure
plt.figure()

# don't use a for i in range loop to loop over array elements
for name in names:
    # use the format function
    filename = '/home/mh/Masters_Project/Sigma/{}.dat'.format(name)

    # use genfromtxt because of better error handling (missing numbers, etc)
    average, sigma = np.genfromtxt(filename, usecols = (0,1), unpack = True, delimiter = ' ')

    plt.xlabel('Magnitude(average)')
    plt.ylabel('$\sigma$')
    plt.plot(average, sigma, marker = '+', linestyle = '', label = name)

plt.legend(loc = 'best')
plt.show()

1 Comment

It's the first time i come across genfromtxt, it is handy and thanks for the update

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.