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.
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!!
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.