Search code examples
pythonmatplotlibplotasciispectrum

How to plot wavelength vs flux from ASCII file


So I am attempting to plot a spectrum of a star from a local ASCII file (the path below in my program is the actual path, I just put a fake one here), but I get a tuple error. I am pretty new to Python as you might be able to tell.

import numpy as np
import astrotools as at
from matplotlib import pyplot as plt
import pyfits 
from astropy.io import fits


def pfit():
    f2 = open('/Users/myname/filepathtoASCIIfile', 'r') 
    lines = f2.readlines()
    f2.close()

    w = []
    f = []

    for line in lines:
        if not line.startswith('#'):
            # if line.endswith('e-16') or line.endswith('e-15'):
            #     line = line[:-4]
            p = line.split()
            if not p[0].startswith('#'):
                try:
                    w.append(float(p[0]))
                    f.append(float(p[1]))
                except IndexError:
                    pass

    W = np.array(w)
    F = np.array(f)
    #return (W, F)

    plt.plot(W, F)
    plt.show()

The error I get when I run this into Python is:

     33 
---> 34     plt.plot(W, F)
     35     plt.show()
     36 

TypeError: 'tuple' object is not callable


Solution

  • Now it may be that the error is elsewhere. There does not seem to be anything badly wrong with your code, and if you have been able to create arrays W and F, your data is quite ok.

    The error hints that something sad has happened to plt.plot. You may have a line somewhere saying:

    plt.plot = ...
    

    for example, you have at some point written:

    plt.plot = (W,F)
    

    and this has overridden the original plt.plot function by a tuple. Now you try to call that tuple, and it does not work.

    To verify if this is the case, add a line before your plotting command:

    print plt.plot
    

    The result should be something like:

    <function plot at 0x10203040>
    

    IF it is not, you have killed your plot command.

    (BTW, thank you for showing the code and the actual error message! And welcome to SO!)