2016-04-27 67 views
0

我在result.csv中有8列,並且需要將圖例添加到我擁有的線圖中。我的代碼是:matplotlib從csv標題行添加圖例到線圖

per_data=genfromtxt('result.csv',delimiter=',') 
plt.plot(per_data) 
plt.xlabel ('x stuff') 
plt.ylabel ('y stuff') 
plt.title('my test result') 
plt.grid() 
plt.show() 

它給了我:

如何添加一個傳奇正好是在我的csv文件標題行?

回答

0

如果使用names=True選項到np.genfromtxt,它將在.csv的第一行中讀取列名稱。

例如:

import matplotlib.pyplot as plt 
import numpy as np 

# Make dummy csv file for this example 
from io import StringIO 
result_csv = StringIO(u""" 
xstuff, data1, data2, data3 
0, 1, 2, 3 
1, 1, 3, 4 
2, 2, 1, 3 
3, 1, 2, 5 
""") 

# Read in csv. Use names=True to also store column headers 
per_data=np.genfromtxt(result_csv,delimiter=',',names=True) 

# Loop over columns. Here I assume you have the x-data in the first column, so skip that one 
for name in per_data.dtype.names[1:]: 
    # Set the line's label to the column name 
    plt.plot(per_data['xstuff'],per_data[name],label=name) 

# Add a legend 
plt.legend(loc=0) 

plt.xlabel ('x stuff') 
plt.ylabel ('y stuff') 
plt.title('my test result') 
plt.grid() 
plt.show() 

enter image description here

+0

謝謝教學中,我學到了很多東西。 –