I have added a text box to matplotlib via the axes.text method. I am wanting to conditionally format the color of the text within this box based on other text. I am including a simplified version to hopefully show the situation a little better.
import matplotlib.pyplot as plt
import yfinance as yf
import pandas_datareader.data as data
from datetime import datetime, timedelta
import mplfinance as mpf
end_date = datetime.today()
start_date = datetime.today() - timedelta(days=20)
df = data.get_data_yahoo('SPY', start_date, end_date)
df['ma'] = df['Close'].rolling(window=5).mean().values
close = df['Close'][-1]
ma = df['ma'][-1]
text_box = r"""Close: {0}
5-MA: {1}""".format(round(close,2), round(ma,2))
fig, axlist = mpf.plot(df,type='candle', returnfig=True, mav=(5), figsize=(8,7), volume=False)
calls_bought = axlist[0].text(0.01, 0.98, text_box, transform=axlist[0].transAxes, verticalalignment='top', horizontalalignment='left', fontsize= 'small', bbox=dict(boxstyle='round', facecolor='white', alpha=0.4))
plt.show()
So in the above example I am wanting to color the text within the box of the closing price if it above or below the moving average.
Thanks for any guidance.
CodePudding user response:
Looks like you should be able to simply change your call to axes.text() to include the "color" argument and pass a value for it based on an in-line if-else statement like the following:
calls_bought = axlist[0].text(
0.01, 0.98, text_box, transform=axlist[0].transAxes,
verticalalignment='top', horizontalalignment='left', fontsize= 'small',
bbox=dict(boxstyle='round', facecolor='white', alpha=0.4),
color="red" if close > ma else "blue"
)