2

So right now, I'm trying to add error bars to an existing graph but I keep running into some errors when I run my code. Below is the code when it works (without the error bars) with my additions commented out. The file that the information is being pulled from contains 4 columns, with the fourth column being the vertical error. When I run the code with the commented out lines included, I get the following error

Traceback (most recent call last):
File "39.py", line 37, in <module>
plot_graph()
File "39.py", line 29, in plot_graph
plt.errorbar(x1,y1, yerr = z1, marker = 'none', linestyle = 'none')
File "/Users/Bashe/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2697, in errorbar
errorevery=errorevery, capthick=capthick, **kwargs)
File "/Users/Bashe/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/axes.py", line 5758, in errorbar
in cbook.safezip(y, yerr)]
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Here is the code I have. Hopefully someone can let me know what's causing this problem.

import os
import pylab as plt

def plot_graph():
    file='Graph.txt'
    x = []
    y = []
    #z = []
    x1 = []
    y1 = []
    #z1 = []
    t = []
    t1 = []
    for dirpath,dirs,files in os.walk('/Users/Bashe/Desktop/121210 p2/'):
        if file in files:
            infile = open(os.path.join(dirpath, "Graph.txt"), "r")
            for columns in (raw.strip().split() for raw in infile):
                t = columns[0]
                x = columns[1]          
                y = columns[2]
                #z = columns[3]
                x1.append(str(x))
                y1.append(str(y))
                #z1.append(str(z))
            t1.append(str(t))
            savepath = os.path.join(dirpath, 'Mean vs Temperature for %s.png' %(t1[0]))
            plt.plot(x1,y1, marker ='o', linestyle = '--')
            #plt.errorbar(x1,y1, yerr = z1, marker = 'none', linestyle = 'none')
            plt.xlabel('Temperature')
            plt.ylabel('Mean')
            plt.title('Mean vs Temperature for %s probe concentration' %(t1[0]))
            plt.savefig(savepath)
            #plt.show()
            infile.close()
3
  • 2
    You should not convert the contents of the plotted columns to str objects. Instead you should do: x1.append(float(x)), etc. Commented Dec 3, 2013 at 1:03
  • 1
    The gist of the error message is that matplotlib is not expecting str objects where you are giving it str objects. Commented Dec 3, 2013 at 1:05
  • 1
    In general, it is best to reduce the code in your question to the minimal amount that will show your problem. Your question has alot of superfluous code (does it matter that you are looping over files? does it matter that you are labeling your axes? does it matter that you are saving the figure?) It looks like you just dumped your entire script here without doing much debugging your self. Commented Dec 3, 2013 at 2:50

3 Answers 3

4

I think you want to be doing something like this:

x1, y1, z1 = [], [], []
with open(fname, 'r') as infile:
    for columns in (raw.strip().split() for raw in infile):
        # convert all of your values floats
        t, x, y, z = [float(v) for v in columns]
        x1.append(x)
        y1.append(y)
        z1.append(z)
# make a figure and an axes object
fig, ax = plt.subplots()
# ax.plot(x1, y1, 'o')
ax.errorbar(x1, y1, yerr=z1, marker='o')

If you have something like csv data, you might also want to look into using the built-in csv module.

It is also good practice to use context managers to open/close files.

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

Comments

2

You are appending the x1 and y1 values as strings to the list and then trying to plot them. Try passing them as floats, which I presume the original x and y are.

Comments

0

I suspect you should be using numpy arrays here. The examples at http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html show that. Try replacing z1 with a numpy array and then you can do z1 = np.append(z1, float(z))

3 Comments

Tried that, it just changes the last line of the error to this TypeError: unsupported operand type(s) for -: 'str' and 'float'
matplotlib will happily eat lists (and turn them into numpy arrays internally)
fixing only z won't help, you need to make all of the number numbers.

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.