Home > Enterprise >  Anchoring text on matplotlib
Anchoring text on matplotlib

Time:06-05

With this code:

from pandas_datareader import data as web
import pandas as pd
import datetime

df = web.DataReader('fb', 'yahoo', start = datetime.date(2022,5,28), end = datetime.datetime.now())
df['pct'] = df.Close.pct_change()
plt.style.use('fivethirtyeight')
plt.rcParams['font.family'] = 'Serif'
fig, ax = plt.subplots()
ax2 = ax.twinx()
plt.axis('off')
df.plot.bar(y = 'pct', ax = ax, grid = True, color = '#bf3c3d')
ax.set_title('Large Title',loc='left', fontname="Times New Roman", size=28,fontweight="bold")
ax.set(xlabel=None)
ax.text(0, 0.07, '\nAttention Catcher', fontsize=13, ha='left')
ax.get_legend().remove()
plt.grid(color = 'green', linestyle = 'dotted', linewidth = 0.5)

This plot is produced:

enter image description here

The issue which I am running into is that I want the text "Attention Catcher" to be lined by exactly on the line where "Large Title" started.

However when the date is changed to produces more bars, the text shifts. So the x,y values of text are dependent on the plot.

enter image description here

What can I do for the text to remain lined up with "Large Title"

I would like it to look like this regardless of the number of bars being plotted. Please help.

enter image description here

CodePudding user response:

By selecting the coordinate system in the string annotation, it can be set to be fixed, independent of the graph size. The value you set was set manually and should be modified.

ax.text(0, 0.07, '\nAttention Catcher', fontsize=13, ha='left')

Change to the following

ax.text(0.08, 1.07, '\nAttention Catcher', ha='left', va='top', fontsize=13, transform=fig.transFigure)

enter image description here

If the subject period is short

enter image description here

  • Related