I have to plot a string and transform its height without changing the width. I do find a Scale class here which does the trick. But, I found there are difference in heights among different letters (see the figure: G, O, C are taller than T, H, A, and exceed the bottom limit).
How can I make all letters with exactly the same height and starting y_axis
?
I tried to use txt1.get_window_extent()
to get the coordinates of the string bbox, but the bbox is not scaled (gray rectangles) after the affine transformation.
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')