Matplotlib计算给定字符串的轴坐标范围 [英] Matplotlib Calculate Axis Coordinate Extents Given String

查看:88
本文介绍了Matplotlib计算给定字符串的轴坐标范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下方式将轴文本对象居中:

I am trying to center an axis text object by:

  1. 获取文本坐标的宽度除以2.
  2. 从 x 轴上的中心(提供)位置减去该值.
  3. 将结果值用作x的起始位置(ha ='left').

我已经看到了绘制这样的字符串后如何获取x坐标(边界)的示例:

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

这是一个可以使用的示例(最后 3 行显示我想要做什么):

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.

我知道我可以使用ha ='center',但这实际上是针对更复杂的文本(多色),它不提供该选项.

I know I can use ha='center', but this is actually for a more complex text (multi-colored), which does not provide that option.

提前致谢!

推荐答案

您可以创建一个文本对象,获取其边界框,然后再次删除该文本.您可以将边界框转换为数据坐标(我假设您是指数据坐标,而不是问题中的坐标轴),然后使用这些坐标来创建左对齐的文本.

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()

这篇关于Matplotlib计算给定字符串的轴坐标范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆