gpt4 book ai didi

python - 在同一图中绘制两个数据不完整的数据集

转载 作者:行者123 更新时间:2023-12-04 09:31:59 27 4
gpt4 key购买 nike

我的数据框由两列组成,每个工作日的股价和每股 yield 。股价仅在工作日可用,而每股 yield 仅在星期六每季度可用。现在我想用两个 y 轴在同一个可视化中绘制两个图形。

            close   eps
date
...
2020-04-01 240.91 NaN
2020-03-31 254.29 NaN
2020-03-30 254.81 NaN
2020-03-28 NaN 2.59
2020-03-27 247.74 NaN
2020-03-26 258.44 NaN
...
2019-12-28 NaN 5.04
2019-12-27 289.80 NaN
...
到目前为止,我的方法是使用 plotly:
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(
x=df.index,
y=df["close"],
name = "Price"
),
secondary_y = False,
)
fig.add_trace(
go.Scatter(
x=df.dropna(subset=["eps"]),
y=df["eps"],
name = "EPS",
),
secondary_y = True,
)


fig.update_yaxes(
title_text="Price",
secondary_y=False
)
fig.update_yaxes(
title_text="EPS",
secondary_y=True,
)

fig.show()
但是,我最终得到了一个图表,但未显示 EPS。我要 eps , 是一条连接点的线,用于 eps 中所有缺失的数据点柱子。
enter image description here

最佳答案

如果您想要一种逐步绘图或只是将点与线连接起来,我不太确定该怎么办。在第一种情况下,我认为您可以使用 df["eps"].fillna(method="ffill")而在第二个 df["eps"].interpolate()生成数据

import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots

df = pd.DataFrame({"date":pd.date_range('2019-01-01', '2020-12-31')})

df["close"] = np.abs(np.random.randn(len(df))) * 300
df["eps"] = np.abs(np.random.randn(len(df))) * 10

df["close"] = np.where(df["date"].dt.weekday>=5,
np.nan,
df["close"])

df["eps"] = np.where((df["date"].dt.month%4==0) &
(df["date"].dt.weekday==5),
df["eps"],
np.nan)

grp = df.set_index("date").groupby(pd.Grouper(freq="M"))["eps"].last().reset_index()

df = df.drop("eps", axis=1)
df = pd.merge(df, grp, how="left", on="date")

df = df.set_index("date")

使用 fillna(method="ffill")
df["eps_fillna"] = df["eps"].fillna(method="ffill")

fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(
x=df.index,
y=df["close"],
name = "Price"
),
secondary_y = False,
)
fig.add_trace(
go.Scatter(
x=df.index,
y=df["eps_fillna"],
name = "EPS",

),
secondary_y = True,
)


fig.update_yaxes(
title_text="Price",
secondary_y=False
)
fig.update_yaxes(
title_text="EPS",
secondary_y=True,
)

fig.show()
enter image description here
使用 interpolate()
df["eps_interpolate"] = df["eps"].interpolate()

fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(
x=df.index,
y=df["close"],
name = "Price"
),
secondary_y = False,
)
fig.add_trace(
go.Scatter(
x=df.index,
y=df["eps_interpolate"],
name = "EPS",

),
secondary_y = True,
)


fig.update_yaxes(
title_text="Price",
secondary_y=False
)
fig.update_yaxes(
title_text="EPS",
secondary_y=True,
)

fig.show()
enter image description here

关于python - 在同一图中绘制两个数据不完整的数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62798268/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com