Tuesday, 21 September 2021

Plotting in a zooming in matplotlib subplot

This question is from this tutorial found here: I want my plot to look like the one below but with time series data and the zoomed data not being x_lim , y_lim data but from a different source. enter image description here

So in the plot above i would like the intraday data that is from a different source and the plot below would be daily data for some stock. But because they both have different source i cannot use a limit to zoom. For this i will be using yahoo datareader for daily and yfinance for intraday.

The code:

import pandas as pd
from pandas_datareader import data as web
from matplotlib.patches import ConnectionPatch

df = web.DataReader('goog', 'yahoo')
df.Close = pd.to_numeric(df['Close'], errors='coerce')

fig = plt.figure(figsize=(6, 5))
plt.subplots_adjust(bottom = 0., left = 0, top = 1., right = 1)
sub1 = fig.add_subplot(2,2,1)
sub1 = df.Close.plot()

sub2 = fig.add_subplot(2,1,2) # two rows, two columns, second cell
df.Close.pct_change().plot(ax =sub2)
sub2.plot(theta, y, color = 'orange')
con1 = ConnectionPatch(xyA=(df[1:2].index, df[2:3].Close), coordsA=sub1.transData, 
                       xyB=(df[4:5].index, df[5:6].Close), coordsB=sub2.transData, color = 'green')
fig.add_artist(con1)

I am having trouble with xy coordinates. With the code above i am getting :

TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

xyA=(df[1:2].index, df[2:3].Close)

What i had done here is that my xvalue is the date df[1:2].index and my y value is the price df[2:3].Close

enter image description here

Is converting the df to an array and then ploting my only option here? If there is any other way to get the ConnectionPatch to work kindly please advise.


df.dtypes

High         float64
Low          float64
Open         float64
Close        float64
Volume         int64
Adj Close    float64
dtype: object


from Plotting in a zooming in matplotlib subplot

No comments:

Post a Comment