mm21
mm21

Reputation: 21

How do add a legend to CSV data plot with no header in Python?

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

Upvotes: 1

Views: 703

Answers (1)

Martin Evans
Martin Evans

Reputation: 46779

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

Upvotes: 3

Related Questions