How to Add Legend for Specific Stock Chart using matplotlib?

Question:

I have this code to plot 3 game corporation stocks. But I want to give legend thus I can know which chart is for EA or for Take Two or for Activision.

from pandas_datareader import data as pdr
import yfinance as yf
import matplotlib.pyplot as plt

yf.pdr_override()
y_symbols = ['EA', 'TTWO', 'ATVI']

from datetime import datetime
startdate = datetime(2000,1,1)
enddate = datetime(2023,1,31)
data = pdr.get_data_yahoo(y_symbols, start=startdate, end=enddate)

#print(data)

#data['Close'].plot()


plt.figure(figsize=(20,10))
plt.plot(data.index, data['Close'])
plt.xlabel("Date")
plt.ylabel("Price (in USD)")
plt.title("Game Corporation Stock Price 1/1/00 - 1/1/23")
plt.show()

1

Thank You.

Asked By: Freya the Goddess

||

Answers:

You can add the label argument to your plot command and then call plt.legend() e.g.:

plt.plot(data.index, data['Close'], label=data["Close"].columns)
plt.legend()
Answered By: Matt Pitkin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.