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 –
JavaScript
x
8
1
titanic = sns.load_dataset('titanic')
2
3
feature = "adult_male"
4
hue = "alive"
5
6
ax = sns.countplot(data=titanic, x=feature);
7
ax.set_title(f"countplot of ${feature}$ by ${hue}$");
8
How do I fix the title?
Advertisement
Answer
This works in a Jupyter Notebook document and a Python console.
JavaScript
1
17
17
1
import seaborn as sns
2
import matplotlib.pyplot as plt
3
4
sns.set(rc={"figure.dpi":300, 'savefig.dpi':300})
5
6
def esc(s):
7
return s.replace("_", "_")
8
9
titanic = sns.load_dataset('titanic')
10
feature = "adult_male"
11
hue = "alive"
12
13
ax = sns.countplot(data=titanic, x=feature);
14
ax.set_title(f"countplot of ${{{esc(feature)}}}$ by ${{{esc(hue)}}}$");
15
16
plt.show()
17
As Trenton kindly pointed out, using an ANSI escape code to italicize doesn’t work when plotting.
JavaScript
1
7
1
def ital(s):
2
return "33[3m" + s + "33[0m"
3
4
feature = "adult_male"
5
hue = "alive"
6
print(f"countplot of {ital(feature)} by {ital(hue)}")
7
The above works.
JavaScript
1
8
1
def ital(s):
2
return "33[3m" + s + "33[0m"
3
4
feature = "adult_male"
5
hue = "alive"
6
ax = sns.countplot(data=titanic, x=feature);
7
ax.set_title(f"countplot of {ital(feature)} by {ital(hue)}");
8
This doesn’t.