I created a Matplotlib plot from a .csv file that shows the 2022 stock returns for Delta Airlines (DAL), United Airlines (UAL), and American Airlines (AAL). Below is the .csv file setup (with theoretical example data, these weren't actual prices):
| Stock Ticker | Date | Close |
|---|---|---|
| DAL | 1/1/2022 | $40.00 |
| DAL | 1/2/2022 | $41.00 |
| ... | ||
| UAL | 1/1/2022 | $35.00 |
| UAL | 1/2/2022 | $33.00 |
| ... | ||
| AAL | 1/1/2022 | $18.00 |
| AAL | 1/2/2022 | $17.00 |
I created 3 plot lines that show the shape of the 2022 stock returns for DAL, UAL, and AAL. I'm trying to figure out how to add labels to each line: DAL, UAL, and AAL. Right now, there are no labels on the lines.
I have the following code right now:
import matplotlib.pyplot as plt
import pandas as pd
file = pd.read_csv('Stock Data.csv')
df = pd.DataFrame(file)
x = df['Date']
y = df['Close']
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x,y)
ax.set_label('Date')
ax.set_label('Close Price')
ax.set_title('Airline Stock Returns')
ax.legend()
plt.show()
I was able to generate and produce a plot, but I'm unable to figure out how to add a stock ticker line label to the 3 lines (for DAL, UAL, and AAL) to show which line plot corresponds with which stock ticker. Any suggestions on this are welcome, including not converting the .csv file to a DataFrame or other solutions.
EDIT: Instead of just using a string text label (e.g. label='DAL'), I want the (label=) portion of the function to read unique values within the Stock Ticker DataFrame column. There will be hundreds of companies I will eventually analyze per industry.
plt.legend(YourDataFrame.columns)?