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
user202729
  • 3,358
  • 3
  • 25
  • 36
mm21
  • 21
  • 3
  • Looks like that you unintentionally make the first row of data into the header. – user202729 Feb 24 '21 at 07:56
  • 1
    Try adding `names` when reading, `aPlot = pd.read_csv('accl/a.csv', names=["col1", "col2", "col3"])` – Martin Evans Feb 24 '21 at 07:57
  • Perhaps [python - Pandas read in table without headers - Stack Overflow](https://stackoverflow.com/questions/29287224/pandas-read-in-table-without-headers) but this one is simpler. – user202729 Feb 24 '21 at 07:59
  • I added `names` when reading, how could I make them the corresponding labels in the legend? – mm21 Feb 24 '21 at 08:02

1 Answers1

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

Martin Evans
  • 45,791
  • 17
  • 81
  • 97