简体   繁体   English

Matplotlib以轴单位表示字体

[英]Matplotlib fontsize in terms of axis units

I'm adding a text field to a plot. 我正在为一个情节添加一个文本字段。 To determine the size of the letters I use fontsize parameter: 要确定字母的大小,我使用fontsize参数:

import matplotlib.pyplot as plt
r = plt.Rectangle((2,2), 10, 10, fill = False)
plt.gca().add_patch(r)
plt.text(7, 7, 'my rectangle', fontsize = 12, ha='center', va='center')
plt.axis(xmin = 0, xmax = 14, ymin = 0, ymax = 14)

I want the text 'my rectangle' to be exactly 2 units (of the y-axis) high. 我想文本'my rectangle'正好是2个单位(y轴)高。 Is there any way to do this? 有没有办法做到这一点?

I doubt this is exactly 2 data units but it looks pretty close: 我怀疑这正是 2个数据单元,但它看起来相当接近:

import matplotlib.pyplot as plt
r = plt.Rectangle((2,2), 10, 10, fill = False)
plt.gca().add_patch(r)
ymin, ymax = (0, 14)
plt.axis(xmin = 0, xmax = 14, ymin=ymin, ymax=ymax)

# Get dimensions of y-axis in pixels
y1, y2 = plt.gca().get_window_extent().get_points()[:, 1]

# Get unit scale
yscale = (y2-y1)/(ymax-ymin)

# We want 2 of these as fontsize
fontsize = 2*yscale
print fontsize, 'pixels'

txt = plt.text(7, 7, u"\u25AF" + 'my rectangle', fontsize=fontsize, ha='center', va='center')

plt.savefig('test.png')

test.png

To get this to work when resizing, you'll need to add a callback. 要在调整大小时使其工作,您需要添加回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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