Search code examples
pythonmatplotlibgraph

How to bold a single word in a string of text in matplotlib?


I am trying to have a graph, table, then text shown as a figure. I was trying to simplify the text by using one ax_text object. However, I cannot figure out how to just bold a single word within the ax_text.annotate() function. I tried weight='bold', but this bolds the entire string. Also, I tried the ASCII \033[0m & \033[1m, but that wasn't working. I could make separate ax_text objects & have one for each bolded word, but figuring out the appropriate xy coordinates would be difficult & could change since the text length can change.

How can I get the annotate call from the ax_text to only bold a single word within the text?

import pandas as pd
import matplotlib.pyplot as plt

fig, (ax, ax_table, ax_text) = plt.subplots(nrows=3, figsize=(10,8), gridspec_kw=dict(height_ratios=[4,1,1]))
tbl = (ax_table.table(rowLabels=["RowLabel1","RowLabel2", 'RowLabel3'], 
        colLabels=['ColLabel1', 'ColLabel2', 'ColLabel3'], 
        cellText=[["1", "2", "3"],
                  ["1", "2", "3"],
                  ["1", "2", "3"]], 
        cellLoc='center',
        loc='center'))

tbl.auto_set_font_size(True)
tbl.set_fontsize(10)
tbl.scale(1,1)
ax_table.axis('off')

text = "This is text. I want the word 'blah' to be Bold."
ax_text.axis('off')
ax_text.annotate(text, wrap=True, xy=(-0.12,1), xycoords='axes fraction', weight='bold', verticalalignment='top')

fig

Solution

  • You can instruct matplotlib to use LaTeX for text formatting: https://matplotlib.org/stable/tutorials/text/usetex.html

    plt.rc('text', usetex=True)
    text = r"This is text. I want the word '\textbf{blah}' to be Bold."
    

    enter image description here