Skip to content
Advertisement

How to italicize a string with underscore in the title of a plot

I would like to title a chart in seaborn as –

countplot of adult_male by alive

I found an old Jupyter Notebook document where someone used $ to wrap around the word to italicize. However, this does not work if there is an underscore. See the code below –

titanic = sns.load_dataset('titanic')

feature = "adult_male"
hue = "alive"

ax = sns.countplot(data=titanic, x=feature);
ax.set_title(f"countplot of ${feature}$ by ${hue}$");

How do I fix the title?

Enter image description here

Advertisement

Answer

This works in a Jupyter Notebook document and a Python console.

import seaborn as sns
import matplotlib.pyplot as plt

sns.set(rc={"figure.dpi":300, 'savefig.dpi':300})

def esc(s):
    return s.replace("_", "_")

titanic = sns.load_dataset('titanic')
feature = "adult_male"
hue = "alive"

ax = sns.countplot(data=titanic, x=feature);
ax.set_title(f"countplot of ${{{esc(feature)}}}$ by ${{{esc(hue)}}}$");

plt.show()

As Trenton kindly pointed out, using an ANSI escape code to italicize doesn’t work when plotting.

def ital(s):
    return "33[3m" + s + "33[0m"

feature = "adult_male"
hue = "alive"
print(f"countplot of {ital(feature)} by {ital(hue)}")

The above works.

def ital(s):
    return "33[3m" + s + "33[0m"

feature = "adult_male"
hue = "alive"
ax = sns.countplot(data=titanic, x=feature);
ax.set_title(f"countplot of {ital(feature)} by {ital(hue)}");

This doesn’t.

Advertisement