我必须绘制一个字符串并变换其高度而不改变宽度。 我确实找到了可以解决问题的Scale类here。但是,我发现不同字母之间的高度有所不同(请参见下图:G,O,C高于T,H,A,并且超过了下限)。
如何使所有字母高度完全相同并以y_axis
开头?
我尝试使用txt1.get_window_extent()
来获取字符串bbox的坐标,但是在仿射变换后bbox并未缩放(灰色矩形)。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import matplotlib.patheffects
# import matplotlib.patches as patches
#-----------------------------------------------------------
class Scale(matplotlib.patheffects.RendererBase):
def __init__(self, sx, sy = None):
self._sx = sx
self._sy = sy
def draw_path(self, renderer, gc, tpath, affine, rgbFace):
affine = affine.identity().scale(self._sx, self._sy) + affine
renderer.draw_path(gc, tpath, affine, rgbFace)
#-----------------------------------------------------------
N=12
fig = plt.figure(figsize = (N+1, 4))
ax = fig.add_subplot(111)
font = FontProperties()
font.set_size(80)
font.set_weight('bold')
font.set_family('monospace')
bbox_props = dict(boxstyle = "square, pad = 0.0", fill = 0, lw = 1, alpha = 0.5)
ax.plot((0.0, 1.0), (0.1, 0.1), linestyle = '--') # dashed line
ax.plot((0.0, 1.0), (0.9, 0.9), linestyle = '--')
txt1 = ax.text(0.3, 0.1, 'GOTCHA',
fontproperties = font,
ha = 'center',
va = 'baseline',
bbox = bbox_props)
txt2 = ax.text(0.8, 0.1, 'GOTCHA',
fontproperties = font,
ha = 'center',
va = 'baseline',
color = 'blue',
bbox = bbox_props)
txt1.set_path_effects([Scale(1.0, 3.0)]) # 3X in height
ax.set_ylim(0.0, 1.0)
plt.savefig('test.png')