Search code examples
pythonmatplotlibtext

Setting part of title as bold and normal in matplotlib


I want to create an axis title that has part of it in bold font.

This is an example of my current code:

# Features to plot
features = ['Overall Rating', 'Shooting Rating', 'Creativity Rating', 'Passing Rating', 
            'Dribbling Rating', 'Defending Rating', 'Pressing Rating', 'Aerial Rating']

# Loop through each feature and create density plots
for i, feature in enumerate(features):
    ax = axes[i]
    # Draw the density plot using the current feature column from the DataFrame
    sns.kdeplot(df[feature], shade=True, color='white', ax=ax)
    # Plot marker for df
    player_value = df[feature].values[0]
    ax.set_title(f'{feature}\n{int(player_value)}', color='#100097', loc='right', fontweight ="bold")

I want the text for feature to be a normal font weight, and for player_value to be a bold font weight.

I've tried various methods to no avail: creating a separate title for each section of text, trying to set the fontweight separately within the set_title function, etc...


Solution

  • You can use LaTeX** to achieve this, quite easily using this kind of expression: $\\bf{bold text}$". In this case, the "bold text" will be displayed as bold.

    So in your case, add this:

    ax.set_title(f'{feature}\n$\\bf{{{int(player_value)}}}$', color='#100097', loc='right')
    

    **: about LaTeX, it seems MathText is what is being called and not LaTeX, I will edit my question later