1

I have a csv file with values that I'd like to plot. The file has no headers as shown below.

          0.95744324  0.09625244  7.9512634
0       0.840118    0.153717   7.841126
1       0.646194    0.292572   7.754929
2       0.492966    0.452988   7.829147
3       0.291855    0.646912   7.991959
4       0.279877    0.716354   8.039841
...          ...         ...        ...

I was able to plot each column as separate lines on a graph with the code below, but I'd like to add a legend for x,y,z dimensions for the corresponding column/line. I am not sure how exactly to go about this as what I have now makes all the keys in the legend 'x'. I cannot modify the csv file, so should I add headers in my code and then plot each column individually?

aPlot = pd.read_csv('accl/a.csv')


plt.figure()
plt.plot(aPlot, label = "x")
plt.xlabel("time")
plt.ylabel("acceleration[m/s^2")
plt.legend(loc="upper left")
plt.show
4
  • Looks like that you unintentionally make the first row of data into the header. Commented Feb 24, 2021 at 7:56
  • 1
    Try adding names when reading, aPlot = pd.read_csv('accl/a.csv', names=["col1", "col2", "col3"]) Commented Feb 24, 2021 at 7:57
  • Perhaps python - Pandas read in table without headers - Stack Overflow but this one is simpler. Commented Feb 24, 2021 at 7:59
  • I added names when reading, how could I make them the corresponding labels in the legend? Commented Feb 24, 2021 at 8:02

1 Answer 1

3

As your CSV file does not have a header, you can specify the column names by passing the names parameter.

You can then use the dataframe to do your plot, the legend will then be correct:

import matplotlib.pyplot as plt
import pandas as pd
 
aPlot = pd.read_csv('input.csv', names=['col1', 'col2', 'col3'])

aPlot.plot()
plt.xlabel("time")
plt.ylabel("acceleration[m/s^2")
plt.legend(loc="upper left")
plt.show()        

Giving you:

matplotlib plot output

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.