2

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
The Rookie
  • 877
  • 8
  • 15
  • 3
    `$...$` is used to enter *math* mode, where an underscore is the subscript operator and variable names are italicized. It should *not* be used simply to italicize arbitrary text. – chepner Jul 07 '22 at 18:14
  • try this adding a back slash (\) before the underscore, it's a wild guess, haven't tested it – pterodactella Jul 07 '22 at 18:15
  • I'm not familiar with `seaborn`, but I assume it either uses behind the scenes or is inspired by `gnuplot`, which allowed (more or less) arbitrary LaTeX code for formatting text. – chepner Jul 07 '22 at 18:22
  • Even if you update the column name to not have `_`, italics don't work with spaces either. See [code and plot](https://i.stack.imgur.com/jT1ni.png) – Trenton McKinney Jul 07 '22 at 19:52
  • See also https://stackoverflow.com/questions/32470137/italic-symbols-in-matplotlib – JohanC Jul 07 '22 at 21:28

1 Answers1

3

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 "\033[3m" + s + "\033[0m"

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

The above works.

def ital(s):
    return "\033[3m" + s + "\033[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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131