Change Seaborn heatmap Y-ticklabels font color for alternate labels
Question:
I have a seaborn heatmap with more than 100 labels on Y-axis. I want to change the font color of the Y-labels to red and blue in alternate way.
If I have 10 Y-labels, then 5 labels should have the blue font & 5 labels should have the red font in an alternate fashion.
Kindly Help
Answers:
you can achieve this using ax.ticklabel.font()
. You can even use font to easily differentiate the neighbors. A sample code is given here.
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
for i, tick_label in enumerate(ax.axes.get_yticklabels()):
if i%2:
tick_label.set_color("blue")
tick_label.set_fontsize("15")
else:
tick_label.set_color("red")
tick_label.set_fontsize("10")
While enumerating as @Redox suggested is necessary, you need a flexible solution in case your label is a string, which is common in heatmaps.
Refer to [matplotlib documentation][1]
for more info.
Credit to @gasvom for inspiring with his answer [here][1]
.
So I would execute as so:
import numpy as np;
import seaborn as sns;
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
for i, tick_label in enumerate(ax.axes.get_yticklabels()):
if tick_label.get_text()=="a string of your choice":
tick_label.set_color("blue")
tick_label.set_fontsize("15")
else:
tick_label.set_color("red")
tick_label.set_fontsize("10")
I have a seaborn heatmap with more than 100 labels on Y-axis. I want to change the font color of the Y-labels to red and blue in alternate way.
If I have 10 Y-labels, then 5 labels should have the blue font & 5 labels should have the red font in an alternate fashion.
Kindly Help
you can achieve this using ax.ticklabel.font()
. You can even use font to easily differentiate the neighbors. A sample code is given here.
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set_theme()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
for i, tick_label in enumerate(ax.axes.get_yticklabels()):
if i%2:
tick_label.set_color("blue")
tick_label.set_fontsize("15")
else:
tick_label.set_color("red")
tick_label.set_fontsize("10")
While enumerating as @Redox suggested is necessary, you need a flexible solution in case your label is a string, which is common in heatmaps.
Refer to [matplotlib documentation][1]
for more info.
Credit to @gasvom for inspiring with his answer [here][1]
.
So I would execute as so:
import numpy as np;
import seaborn as sns;
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
for i, tick_label in enumerate(ax.axes.get_yticklabels()):
if tick_label.get_text()=="a string of your choice":
tick_label.set_color("blue")
tick_label.set_fontsize("15")
else:
tick_label.set_color("red")
tick_label.set_fontsize("10")