python - 使用 matplotlib 向图形添加误差线

标签 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()

最佳答案

我想你想做这样的事情:

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 .

使用上下文管理器打开/关闭文件也是一种很好的做法。

关于python - 使用 matplotlib 向图形添加误差线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340359/

相关文章:

python - 如何使用 MATPLOTLIB 设置标签?

python - 如何使用词袋或tf-idf对文本进行分类

python - django celery 延迟函数不执行

python - matplotlib动画可以保存成什么格式?

python - Matplotlib:如何绘制具有不同颜色和注释的簇?

python - mplot3d 中的 z 轴格式

python - matplotlib 绘制了太多刻度

python - 解析嵌套的三元表达式

Python套接字发送问题

python - 由于索引,两个 Pandas 系列相乘会产生 NaN 条目