python - 在同一个图中绘制两个数据不完整的数据集
问题描述
我的数据框由两列组成,每个工作日的股价和每股收益。股价仅在工作日可用,而每股收益仅在星期六每季度可用。现在我想用两个 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
。
解决方案
我不太确定如果你想要一种逐步的情节或者只是用一条线连接点。在第一种情况下,我认为您可以df["eps"].fillna(method="ffill")
在第二种情况下使用 whiledf["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()
使用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()
推荐阅读
- html - 填写第 3 方 htacces
- javascript - 'selectedHandler' 不是函数,Node JS
- api - 当我提出请求时,URL 中的参数在哪里?
- azure-devops - Azure 管道复制文件任务
- asp.net-identity - Asp.Net Identity 检查 tokenlifespan 时间为两个因素
- javascript - 带有时间戳的对象数组的日期过滤[图表添加]
- snakemake - 用于输出文件命名的 Snakefile 和通配符/正则表达式
- python - scikit-learn 在 make_scorer 中苦苦挣扎
- javascript - 终止 JavaScript 中的处理程序执行
- android - Android Studio 错误:程序类型已存在:org.objectweb.asm.Edge