【发布时间】:2013-12-03 12:10:21
【问题描述】:
所以现在,我正在尝试向现有图表添加错误栏,但在运行代码时我不断遇到一些错误。下面是它工作时的代码(没有错误栏),我的添加被注释掉了。从中提取信息的文件包含 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()
【问题讨论】:
-
您不应将绘制列的内容转换为
str对象。相反,您应该这样做:x1.append(float(x))等。 -
错误消息的要点是
matplotlib不期望str对象,而你给它的是str对象。 -
一般来说,最好将问题中的代码减少到能显示问题的最少数量。你的问题有很多多余的代码(你循环文件有关系吗?你标记你的轴有关系吗?你保存这个数字有关系吗?)看起来你只是在这里倾倒了你的整个脚本做很多调试自己。
标签: python matplotlib