0

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.

5
  • Does this answer your question? How to label a line in matplotlib (python)? Commented Mar 13, 2023 at 23:00
  • @MarceloPaco It's close, the addendum to that is that I would like the labels to be unique values within the Stock Ticker DataFrame column (if using Pandas) instead of just a string text label. I will edit my post to clarify. Commented Mar 13, 2023 at 23:28
  • Did you try this: plt.legend(YourDataFrame.columns)? Commented Mar 13, 2023 at 23:37
  • @MarceloPaco I'll take a look and get back to this post. Commented Mar 13, 2023 at 23:45
  • UPDATE: I was able to use the information in stackoverflow.com/questions/63804460/… to answer my question. Feel free to close this out. Commented Mar 14, 2023 at 0:28

0

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.