如何在 Python Pandas 数据帧的时间序列图上添加信号点?
How to add signal dots on time-series plot for Python Pandas dataframe?
我有一个数据框,其中包含两个变量 Reported_Cases
和 Horizontal_Threshold
的时间序列数据,这是我的图形代码:
def time_series_graph_horizontal_threshold(df, x_var, y_var):
plt.figure(figsize=(10, 6))
plt.grid(True)
df.plot(x='Year_Week', y=['Reported_Cases', 'Horizontal_Threshold'])
plt.show()
生成此图
如何在图表上添加正信号,以便当 Reported_Cases
高于 Horizontal_Threshold
时,它会在图表中显示绿色信号点?我们可以假设我有另一个名为 Positive_Signal
的列,它是二进制的 (0, 1=above).
首先绘制图像,但保存结果(轴对象):
ax = df.plot(x='Year_Week', y=['Reported_Cases', 'Horizontal_Threshold'], grid=True, rot=45)
不需要单独调用plt.grid(True)
,也许你应该添加参数
关于图像大小。
然后在上面加上绿点:
ht = df.iloc[0].Horizontal_Threshold
dotY = 280 # Y coordinate of green points
hDist = 2 # Number of weeks between green points
for idx, rc in df.Reported_Cases.items():
if idx % hDist == 0 and rc > ht:
ax.plot(idx, dotY, '.g')
写上面的代码我假设你的DataFrame有索引由连续的整数组成。
也许你应该设置 dotY 和 hDist 的其他值。实际上 hDist 取决于
关于源行的数量以及这些点的所需“密度”如何。
对于包含 40 行(周)的测试数据,我得到:
我有一个数据框,其中包含两个变量 Reported_Cases
和 Horizontal_Threshold
的时间序列数据,这是我的图形代码:
def time_series_graph_horizontal_threshold(df, x_var, y_var):
plt.figure(figsize=(10, 6))
plt.grid(True)
df.plot(x='Year_Week', y=['Reported_Cases', 'Horizontal_Threshold'])
plt.show()
生成此图
如何在图表上添加正信号,以便当 Reported_Cases
高于 Horizontal_Threshold
时,它会在图表中显示绿色信号点?我们可以假设我有另一个名为 Positive_Signal
的列,它是二进制的 (0, 1=above).
首先绘制图像,但保存结果(轴对象):
ax = df.plot(x='Year_Week', y=['Reported_Cases', 'Horizontal_Threshold'], grid=True, rot=45)
不需要单独调用plt.grid(True)
,也许你应该添加参数
关于图像大小。
然后在上面加上绿点:
ht = df.iloc[0].Horizontal_Threshold
dotY = 280 # Y coordinate of green points
hDist = 2 # Number of weeks between green points
for idx, rc in df.Reported_Cases.items():
if idx % hDist == 0 and rc > ht:
ax.plot(idx, dotY, '.g')
写上面的代码我假设你的DataFrame有索引由连续的整数组成。
也许你应该设置 dotY 和 hDist 的其他值。实际上 hDist 取决于 关于源行的数量以及这些点的所需“密度”如何。
对于包含 40 行(周)的测试数据,我得到: