1

I have 3 pandas series plotted where the values are:

date_series = date1,date2... 
price_series = price1,price2... 
factor_series = factor1,factor2...

and so i wish to annotate/highlight it on a matplotlib figure automatically based on an if condition which is when factor_series > 4 or factor_series < -4. If factor series value meets either condition, then annotate on the figure the factor value with some marker and that specific factor value in text. It would look something like the green circle and text in the picture.

charting example

I'm unsure of how to apply a function to check for the if condition with annotate and so I'm hoping to get some ideas here. Thank you in advance!!

2
  • 1
    you could create sub arrays where the conditions apply and plot it on top with the desired color. Commented Mar 27, 2021 at 15:44
  • maybe a duplicate of this: stackoverflow.com/questions/29604080/… Commented Mar 27, 2021 at 15:46

1 Answer 1

3

If possible, I would recommend putting your series together in a DataFrame indexed by date for easier access. Then you can add a scatterplot of the subset DataFrame: df[df['factor'] > 4] to your secondary y-axis object with corresponding text and markers.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

np.random.seed(42)
date_index = pd.date_range(start='2006', end='2020', freq='M')
df = pd.DataFrame(data={
    'price':np.random.normal(loc=100, scale=20.0, size=len(date_index)),
    'factor':np.random.normal(loc=2.0, scale=1.0, size=len(date_index))
    },index=date_index)

## create a figure and use a secondary y-axis 
fig = plt.figure(figsize=(12,5))
ax = fig.add_subplot(111)
ax.plot(df.index, df.price, color="red")

ax2=ax.twinx()
ax2.plot(df.index, df.factor, color="blue")

# Add markers and corresponding text by looping through the 
for date_value, factor_value in df[df['factor'] > 4].factor.items():
    ax2.scatter(date_value, factor_value, facecolors='none', edgecolors='g')
    ax2.text(date_value, factor_value+0.25, f"{factor_value:.2f}")

fig.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.