Python 如何将matplotlib中折线图上的各个像素坐标返回到新的DataFrame列中?

Python 如何将matplotlib中折线图上的各个像素坐标返回到新的DataFrame列中?,python,pandas,matplotlib,Python,Pandas,Matplotlib,我想在我的df中添加一列,以显示绘制为折线图的点的像素坐标。我的目标是获得在不同y轴上彼此重叠的两个折线图的y坐标,并找出每对y坐标之间的差异 我从另一个类似的例子中获得灵感,并尝试应用它。代码此时失败: fig_main.transData.transform(np.vstack([x,y]).T) 错误是: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe' 我想很

我想在我的df中添加一列,以显示绘制为折线图的点的像素坐标。我的目标是获得在不同y轴上彼此重叠的两个折线图的y坐标,并找出每对y坐标之间的差异

我从另一个类似的例子中获得灵感,并尝试应用它。代码此时失败:

fig_main.transData.transform(np.vstack([x,y]).T)
错误是:

Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
我想很明显我不明白我到底在这里干什么

我的代码如下:

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,:])

您可以取消最后一行的注释以查看数据框,否则您应该会看到图表

请将您的代码缩减为一个。它需要两行代码,没有if子句和代码中创建的数据。我已经缩短了代码的长度,注释出了每个段的用途。正在讨论的段是#尝试获取坐标。我还添加了另一个答案的链接,我试图在这里应用该答案,但失败了。您是否可以创建一个,而不使用
investpy
(这对我来说还不够普遍)?