Home > Blockchain >  How to add signal dots on time-series plot for Python Pandas dataframe?
How to add signal dots on time-series plot for Python Pandas dataframe?

Time:10-30

I have a dataframe with time-series data on two variables Reported_Cases and Horizontal_Threshold, here is my graph code:

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()

Which generates this graph

enter image description here

How can I add positive signals on the graph such that when the Reported_Cases is higher than the Horizontal_Threshold, it will show green signal dots across the graph? We can assume I have another column named Positive_Signal which is binary (0, 1=above).

enter image description here

CodePudding user response:

First draw your image, but saving the result (axes object):

ax = df.plot(x='Year_Week', y=['Reported_Cases', 'Horizontal_Threshold'], grid=True, rot=45)

No need to call plt.grid(True) separately, maybe you should add parameters concerning the image size.

Then impose green points on it:

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')

Writing the above code I assumed that your DataFrame has the index composed of consecutive integers.

Maybe you should set other values of dotY and hDist. Actually hDist depends on the number of source rows and how is the desired "density" of these points.

For my test data containing 40 rows (weeks) I got:

enter image description here

  • Related