I am trying to center an axis text object by:
- Getting the width in coordinates of the text divided by 2.
- Subtracting that value from the center (provided) location on the x-axis.
- Using the resulting value as the x starting position (with ha='left').
I have seen examples of how to get x-coordinates (bounds) after plotting a string like this:
import matplotlib as plt
f = plt.figure()
r = f.canvas.get_renderer()
t = plt.text(0, 0, 'test')
bb = t.get_window_extent(renderer=r)
width = bb.width
However, I would like to know the width (in axis coordinates) of a string before plotting so that I can anticipate an adjustment to make.
I've tried the following, but it did not return the correct axis coordinates and I think a transformation may need to occur:
t = matplotlib.textpath.TextPath((0,0), 'test', size=9)
bb = t.get_extents()
w = bb.width #16.826132812499999
Here's a sample to work with (last 3 lines show what I want to do):
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
%matplotlib inline
prf=[60,70,65,83,77,70,71]
figsize=3.5,4
fig, ax = plt.subplots(1, 1, figsize = figsize, dpi=300)
ind=np.arange(len(prf))
p=ax.bar(ind,prf,color=colrs,edgecolor='none')
t = matplotlib.textpath.TextPath((0,0), 'test', size=9)
bb = t.get_extents()
w = bb.width
center=len(ind)/2
xposition=center-w/2
ax.text(xposition,110,'test',size=9)
This question is a follow-up from this post.
I know I can use ha='center', but this is actually for a more complex text (multi-colored), which does not provide that option.
Thanks in advance!