使用matplotlib向图表添加错误栏

时间:2013-12-03 00:07:39

标签: python matplotlib

现在,我正在尝试向现有图表添加错误栏,但在运行代码时遇到了一些错误。下面是代码工作时(没有错误栏)我的添加内容被注释掉了。从中提取信息的文件包含4列,第四列是垂直错误。当我运行带有注释掉的行的代码时,我收到以下错误

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'

这是我的代码。希望有人能告诉我导致这个问题的原因。

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 个答案:

答案 0 :(得分:3)

我想你想做这样的事情:

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')

如果你有类似csv数据的内容,你可能还想研究使用内置的csv module

使用上下文管理器打开/关闭文件也是一种好习惯。

答案 1 :(得分:2)

您要将x1y1值作为字符串追加到列表中,然后尝试绘制它们。尝试将它们作为浮点数传递,我认为它是原始的xy

答案 2 :(得分:0)

我怀疑你应该在这里使用numpy数组。 http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html的例子表明了这一点。尝试用numpy数组替换z1,然后你可以做z1 = np.append(z1,float(z))