我有一个关于用python绘制csv数据的天真问题。
我有一个csv文件,如下所示:
SubjID SubjGrp GoRT SSRT StopPoss
1 control 568.56 320.22 0.58
2 control 680.08 314.84 0.54
我想绘制如下数据:
我尝试了以下语法:
import numpy as np
import matplotlib.pyplot as plt
d1=csv2rec('stop-allrun-2.csv',delimiter='\t', names=['SubjID', 'GoRT','SSRT','StopPoss'])
x=d1['SubjID']
y=['GoRT']
plot(x,y)
然后弹出错误信息:
ValueError:x和y必须具有相同的第一维
我有什么办法可以改进这个脚本吗?
答案 0 :(得分:1)
将空格用作分隔符(' '
),然后获取除列名称以外的所有数据,并将其从字符串转换为整数或浮点数。
import numpy as np
from matplotlib.pyplot import *
from matplotlib.mlab import *
d1=csv2rec('stop-allrun-2.csv',delimiter=' ', names=['SubjID', 'SubjGrp', 'GoRT','SSRT','StopPoss'])
x = tuple(d1['SubjID'][1:])
subjid = tuple(map(int, d1['SubjID'][1:]))
gorts = tuple(map(float, d1['GoRT'][1:]))
ssrts = tuple(map(float, d1['SSRT'][1:]))
width = 0.35
ind = np.arange(len(x))
print(x, gorts, ind)
fig, ax = subplots()
rects1 = ax.bar(ind - width, subjid, width, color = 'y')
rects2 = ax.bar(ind, gorts, width, color = 'r')
rects3 = ax.bar(ind + width, ssrts, width, color = 'b')
ax.set_ylabel('msec')
ax.set_xticks(ind)
ax.set_xticklabels(x)
ax.legend((rects1[0], rects2[0], rects3[0]), ('SubjID', 'GoRT', 'SSRT'))
show()
结果如下:
它应该同时适用于pyhon2和python3。
答案 1 :(得分:1)
试试这个
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
d1=mlab.csv2rec('stop-allrun-2.csv',skiprows=1,delimiter='\t', names=['SubjID','SubjGrp', 'GoRT','SSRT','StopPoss'])#.astype('float')
x=d1['SubjID']
y=d1['GoRT']
plt.plot(x,y)