2

I have 8 columns in my result.csv, and need to add legend to the line graph I have. My code is:

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()

it gives me:

Result of 8 line graph how can I add a legend which happened to be the title row in my csv file?

1 Answer 1

2

If you use the names=True option to np.genfromtxt, it will read in the first line of the .csv as the column names.

For example:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.