0

I want to be able to have labels on each of the lines that are being plotted but when I attempt to add label="MSFT" and of "AAPL" to ax1.plot(..., label="MSFT") and ax1.plot(..., label="AAPL"), the label still does not show up for those two but does show up for TSLA.

Further, is it possible be able to see the graph of a certain interval without going back and having to change the start and end time. I tried doing df.index['2020-01-01':'2020-05-14'] but was unsuccessful.

import matplotlib.pyplot as plt
import pandas_datareader as web
import datetime as dt

# style.use('ggplot')
start = dt.datetime(2020,1,1)
end = dt.datetime(2020,5,14)

df = web.DataReader('MSFT', 'yahoo', start, end)
df2 = web.DataReader('AAPL', 'yahoo', start, end)
df3 = web.DataReader('TSLA', 'yahoo', start, end)

ax1 = plt.subplot2grid((6,1),(0,0), rowspan=5, colspan=1)
plt.title("Stocks")
plt.xlabel("Date")
plt.ylabel("Adj Close Price")

ax2 = plt.subplot2grid((6,1),(5,0), rowspan=1, colspan=1, sharex=ax1)
plt.xlabel("Date")
plt.ylabel("Adj Close Price")

ax1.plot(df.index, df['Adj Close'], label="MSFT")
ax1.plot(df.index, df2['Adj Close'], label="AAPL")
ax2.plot(df.index, df3['Adj Close'], label="TSLA")

plt.legend()
plt.show()
JohanC
  • 71,591
  • 8
  • 33
  • 66
KiosGames
  • 1
  • 1
  • See [this post](https://stackoverflow.com/a/10129461/12046409) about how to combine the legend entries of both axes. Or you could simply call `ax1.legend()` and `ax2.legend()` separately. – JohanC May 15 '20 at 22:31
  • To change the displayed interval, you can use `ax1.set_xlim(dt.datetime(2020, 2, 1), dt.datetime(2020, 5, 14))` – JohanC May 15 '20 at 22:34

0 Answers0