0

Am using following code to print to plot stock prices and a vertical line on one graph. But of them work individually but i cant plot both on one graph

import datetime as dt
import yfinance as yf
import matplotlib.pyplot as plt

# Get the data for the stock Apple by specifying the stock ticker, start date, and end date
data = yf.download('AAPL','2020-02-01','2020-02-10', interval='15m')


data.Close.plot(figsize=(10, 5))
plt.axvline(dt.datetime(2020, 2, 2)) ## No effect if previous line is there. 

plt.show()

The vertical line is shown only if i comment data.Close.plot(figsize=(10, 5)) line

SKPS
  • 5,433
  • 5
  • 29
  • 63
user93796
  • 18,749
  • 31
  • 94
  • 150

1 Answers1

1

Its always good to get the figure and the axes handles such that subsequent manipulation can be done easily.

import datetime as dt
import yfinance as yf
import matplotlib.pyplot as plt
# added following line to avoid a warning of future support of datetime
# https://github.com/pandas-dev/pandas/issues/18301#issuecomment-344580274
from pandas.plotting import register_matplotlib_converters

# Get the data for the stock Apple by specifying the stock ticker, start date, and end date
data = yf.download('AAPL','2020-02-01','2020-02-10', interval='15m')
register_matplotlib_converters()
fig, ax = plt.subplots(1, figsize=(10, 5))
ax.plot(data.Close)
ax.axvline(dt.datetime(2020, 2, 2), color='red')
plt.show()

enter image description here

SKPS
  • 5,433
  • 5
  • 29
  • 63
  • That worked. How do i show two graphs on same graph with different scales on on right side and one on left? As of now if i do that one graph looks flat horizontal as the value of other graph are too big – user93796 Feb 17 '20 at 00:14
  • 1
    You mean `twinx`? https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/two_scales.html#sphx-glr-gallery-subplots-axes-and-figures-two-scales-py – SKPS Feb 17 '20 at 01:27