1

I have a list of names like

names = ['a b c', 'd e f', ...]

and I need to print these names in a plot using bold for some of them. So I'm using for example

for k in range(len(names)):
    if k in [0,2]:
       plt.text(x,y, '$\\bf{' + names[k] + '}$')
    else:
       plt.text(x,y, names[k])

but in this way names in bold are printed like abc instead of a b c. Of course '$\\bf{names[k]}$' just prints names[k]. What is the correct way of doing this?

I have also tried the answers here link without any luck.

EternalGenin
  • 495
  • 2
  • 6
  • 14

1 Answers1

1

Using mathtext has the unfortunate side-effect of stripping spaces. You need to escape the spaces (with \) to make it work.

However, if you don't specifically need to use mathtext, I would suggest you use the fontdict= option to Text to change the weight to bold.

Here is how I would do it:

names = ['a b c', 'd e f', 'g h i']
bold = [True, False, True]
xys = [(-3,-1),(0,0),(2,1)]
for n,doBold,xy in zip(names,bold,xys):
    t = ax.text(*xy, n, fontdict={'fontweight': 'bold' if doBold else 'normal'})

enter image description here

Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75