Matplotlib:使用.csv直接导入和绘制多个时间序列

我有几个电子表格包含以逗号分隔(.csv)文件保存为以下格式的数据:第一行包含列标签作为string('时间','Parameter_1'…)。 数据的第一列是时间,每个后续列都包含相应的参数数据,如浮点数或整数。

我想在同一个图上绘制每个参数与时间的关系,参数图例直接来自.csv文件的第一行。

我的电子表格具有不同数量的(列)参数,可以根据时间绘制; 所以我想find一个通用的解决scheme,这也将直接从.csv文件派生的列数。

附加的最小工作示例显示了我试图使用np.loadtxt(减去图例)实现的; 但我找不到从.csv文件中导入列标签以使用此方法制作图例的方法。

np.genfromtext提供了更多的function,但我不熟悉这一点,并正在努力find一种方法来使用它来做到上述。

从.csv文件中以这种风格绘制数据必须是一个常见问题,但是我一直无法在网上find解决scheme。 我非常感谢您的帮助和build议。

非常感谢

""" Example data: Data.csv: Time,Parameter_1,Parameter_2,Parameter_3 0,10,0,10 1,20,30,10 2,40,20,20 3,20,10,30 """ import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('Data.csv', skiprows=1, delimiter=',') # skip the column labels cols = data.shape[1] # get the number of columns in the array for n in range (1,cols): plt.plot(data[:,0],data[:,n]) # plot each parameter against time plt.xlabel('Time',fontsize=14) plt.ylabel('Parameter values',fontsize=14) plt.show() 

函数numpy.genfromtxt更多的是缺less值而不是你想要做的事情。 你可以做的只是打开文件,然后把它交给numpy.loadtxt并阅读第一行。 那么你甚至不需要跳过它。 这里是你在上面读到的标签和使图例的编辑版本:

 """ Example data: Data.csv: Time,Parameter_1,Parameter_2,Parameter_3 0,10,0,10 1,20,30,10 2,40,20,20 3,20,10,30 """ import numpy as np import matplotlib.pyplot as plt #open the file with open('Data.csv') as f: #read the names of the colums first names = f.readline().strip().split(',') #np.loadtxt can also handle already open files data = np.loadtxt(f, delimiter=',') # no skip needed anymore cols = data.shape[1] for n in range (1,cols): #labels go in here plt.plot(data[:,0],data[:,n],label=names[n]) plt.xlabel('Time',fontsize=14) plt.ylabel('Parameter values',fontsize=14) #And finally the legend is made plt.legend() plt.show() 

这是我上面使用genfromtxt而不是loadtxt的最小工作示例,以防其他人帮忙。 我确信有更简洁和优雅的方法来做这件事(我总是乐于得到build设性的批评,如何改善我的编码),但它是有道理的,工作正常:

 import numpy as np import matplotlib.pyplot as plt arr = np.genfromtxt('Data.csv', delimiter=',', dtype=None) # dtype=None automatically defines appropriate format (eg string, int, etc.) based on cell contents names = (arr[0]) # select the first row of data = column names for n in range (1,len(names)): # plot each column in turn against column 0 (= time) plt.plot (arr[1:,0],arr[1:,n],label=names[n]) # omitting the first row ( = column names) plt.legend() plt.show()