0

I would like to add a column in my df to show the pixel coordinates of points plotted as a line chart. My goal is to obtain the y-coordinates of two line charts that have been overlaid on each other on different y-axes and find the difference between each pair of y-coordinates.

I took inspiration from this other StackOverflow answer similar to it and tried to apply it. The code failed at this point:

fig_main.transData.transform(np.vstack([x,y]).T)

Error was:

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

I think it's pretty obvious I don't actually understand what the heck I'm doing here.

My code is as such:

import investpy
import pandas as pd
import matplotlib

#raw data
spot_df = investpy.get_currency_cross_historical_data(currency_cross = "AUD/SGD", from_date = "01/01/2018", to_date = "05/02/2020")
base_yield_df = investpy.bonds.get_bond_historical_data(bond = "Australia 2Y", country = "Australia", from_date = "01/01/2018", to_date = "05/02/2020")
quote_yield_df = investpy.bonds.get_bond_historical_data(bond = "Singapore 2Y", country = "Singapore", from_date = "01/01/2018", to_date = "05/02/2020")

#data munging
df = pd.merge(spot_df["Close"],base_yield_df["Close"], how='inner', left_index=True, right_index=True)
df = pd.merge(df, quote_yield_df["Close"], how='inner', left_index=True, right_index=True)
df.columns = ["AUD/SGD", "base", "quote"]
df["2Y Spread"] = df["base"]/df["quote"]
df

#creating subplot
fig = plt.figure(figsize = [15, 9] )
gs = fig.add_gridspec(3, 2)
fig_main = fig.add_subplot(gs[0:2,:])

#plotting data points
points, = fig_main.plot(df["2Y Spread"], label = "2Y Spread", color = "red")

fig_main = fig_main.twinx()
fig_main.plot(df["AUD/SGD"], label = "AUD/SGD", color = "green")

#attempt to obtain coordinates of data points 
x, y = points.get_data()
xy_pixels = fig_main.transData.transform(np.vstack([x,y]).T)
xpix, ypix = xy_pixels.T
xpxi, ypix

#another subplot to display the difference in y-coordinate of the two line graphs
fig_main = fig.add_subplot(gs[2,:])

You can uncomment the final line to see the dataframe, otherwise you should see the chart.

moron
  • 51
  • 1
  • 9
  • Please reduce your code to a [mcve]. It needs two lines, no if-clauses and data created within the code. – ImportanceOfBeingErnest Jan 25 '20 at 16:14
  • I have cut down on the length of code, commenting out the purpose of each segment. The segment in question is #attempt to obtain coordinates. I have also added in the link to another answer which I tried to apply here but failed – moron Feb 06 '20 at 16:05
  • Can you create a [mcve], without using `investpy` (which is not common enough for me to have it)? – ImportanceOfBeingErnest Feb 07 '20 at 00:04

0 Answers0