Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib scale text (curly brackets)

I would like to use curly brackets '}' in my plot all having different heights, but the same width. So far when scaling the text, the width scales proportionally:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.text(0.2, 0.2, '}', fontsize=20)
ax.text(0.4, 0.2, '}', fontsize=40)
plt.show()

The only idea that comes to my mind is overlaying images of braces with the matplotlib image, e.g. using svgutils like in Importing an svg file a matplotlib figure, but this is cumbersome.

A solution with vector graphics as output would be ideal.

like image 201
gizzmole Avatar asked Aug 30 '25 15:08

gizzmole


1 Answers

To get a letter in scaled only in one dimension, e.g. height but keeping the other dimension constant, you may create the curly bracket as TextPath. This can be provided as input for a PathPatch. And the PathPatch may be scaled arbitrarily using matplotlib.transforms.

import matplotlib.transforms as mtrans
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

def curly(x,y, scale, ax=None):
    if not ax: ax=plt.gca()
    tp = TextPath((0, 0), "}", size=1)
    trans = mtrans.Affine2D().scale(1, scale) + \
        mtrans.Affine2D().translate(x,y) + ax.transData
    pp = PathPatch(tp, lw=0, fc="k", transform=trans)
    ax.add_artist(pp)

X = [0,1,2,3,4]
Y = [1,1,2,2,3]
S = [1,2,3,4,1]

for x,y,s in zip(X,Y,S):
    curly(x,y,s, ax=ax)

ax.axis([0,5,0,7])
plt.show()

enter image description here

like image 147
ImportanceOfBeingErnest Avatar answered Sep 02 '25 11:09

ImportanceOfBeingErnest