简体   繁体   中英

Matplotlib Calculate Axis Coordinate Extents Given String

I am trying to center an axis text object by:

  1. Getting the width in coordinates of the text divided by 2.
  2. Subtracting that value from the center (provided) location on the x-axis.
  3. 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!

You can create a text object, obtain its bounding box and then remove the text again. You may transform the bounding box into data coordinates (I assume that you mean data coordinates, not axes coordinates in the question) and use those to create a left aligned text.

import matplotlib.pyplot as plt

ax = plt.gca()
ax.set_xlim(0,900)
#create centered text 
text = ax.text(400,0.5, "string", ha="center", color="blue")
plt.gcf().canvas.draw()
bb = text.get_window_extent()
# remove centered text
text.remove()
del text
# create left aligned text from position of centered text
bb2 = bb.transformed(ax.transData.inverted())
text = ax.text(bb2.x0,0.5, "string", ha="left", color="red")

plt.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM