PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, June 28, 2022

[FIXED] How to add signal dots on time-series plot for Python Pandas dataframe?

 June 28, 2022     graph, pandas, python-3.x     No comments   

Issue

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


Solution

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



Answered By - Valdi_Bo
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing