I am trying to add text to a matplotlib axis in Python.
Here is the set up:
import matplotlib.pyplot as plt
s = 'This is a {}'.format('string')
fig,ax = plt.subplots()
ax.text(x=0.5,y=0.5,s=s,ha='center',va='center',fontweight='normal')
That produces this outcome:
Specifically, what I want to do is make ONLY the word 'string' itself bold. I have looked for ways to do this, but not been successful so far.
I have specifically set the s string up by deploying the word 'string' itself via the format method into the string, since I thought perhaps there is some way of attaching formatting parameters to the string then?
It seems in the ax.text options that I can only effect the weighting of the overall string by adjusting the fontweight parameter.
Is there an easy way to do this? If not, perhaps a way of incorporating html syntax?
Thank you for any solution! The most simple (I assume also therefore pythonic) is what I am really looking for!
Thanks!
Further edit in response to the possible solution using MathText. If I wanted the string to be much longer and include line breaks, it is not clear how to also insert the line breaks without escaping the bold formatting.
Example:
import matplotlib.pyplot as plt
s = 'This is a' + r'$\bf{}$'.format('string, that is much longer than the last string. I would like to insert a line break here. Then continue with the sentence on a new line.')
fig,ax = plt.subplots(figsize=(20,10))
ax.text(x=0.5,y=0.5,s=s,ha='center',va='center',fontsize=12,fontweight='normal')
produces:
However, if I insert a line break, it seems to escape the bold formatting:
import matplotlib.pyplot as plt
s = 'This is a' + r'$\bf{}$'.format('string, that is much longer than the last string. I would like to insert a line break here.\n Then continue with the sentence on a new line.')
fig,ax = plt.subplots(figsize=(20,10))
ax.text(x=0.5,y=0.5,s=s,ha='center',va='center',fontsize=12,fontweight='normal')
produces:
Note: It is also important that I be able to deploy the line breaks within the string itself, rather than adding multiple strings, since this is a process that I want to repeat over and over again as the output of other code i.e. not to have to fix by manually splitting up the string.
I realise that this may be slighty off topic now, but this is the culmination of the question! Thanks!