2016-04-27 13 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

オプションを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

おかげで、私は多くのことを学びました。 –